不能对具有相同ID的元素触发点击事件 [英] Can't fire click event on the elements with same id

查看:52
本文介绍了不能对具有相同ID的元素触发点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能帮我理解-我在哪里弄错了.我有以下html代码:

Could you help me to understand - where I made the mistake. I have the following html code:

<div id="container">
    <a href="#info-mail.ru" id="getInfo" onClick="return false;">Info mail.ru</a>
</div>
<div id="container">
    <a href="#info-mail.com" id="getInfo" onClick="return false;">Info mail.com</a>
</div>
<div id="container">
    <a href="#info-mail.net" id="getInfo" onClick="return false;">Info mail.net</a>
</div>

和以下js代码(使用jQuery):

and the following js code (using jQuery):

$('#getInfo').click(function(){
    alert('test!');
});

此处的示例

点击"事件仅在第一个链接元素上触发.但对其他人却没有.

"Click" event fired only on first link element. But not on others.

我知道html页面中的每个 ID 应该只能使用一次(但是 CLASS 可以使用很多次)-但只能(不是必须),据我所知.这是我问题的根源吗?

I know that each ID in html page should be used only one time (but CLASS can be used a lot of times) - but it only should (not must) as I know. Is it the root of my problem?

TIA!

更新:非常感谢大家的解释!:)

upd: Big thx to all for explanation!:)

推荐答案

为此使用一个类(并且在处理程序中而不是内联地 return false ):

Use a class for this (and return false in your handler, not inline):

<div id="container">
    <a href="#info-mail.ru" class="getInfo">Info mail.ru</a>
</div>
<div id="container">
    <a href="#info-mail.com" class="getInfo">Info mail.com</a>
</div>
<div id="container">
    <a href="#info-mail.net" class="getInfo">Info mail.net</a>
</div>

$('.getInfo').click(function(){
    alert('test!');
    return false;
});

http://jsfiddle.net/Xde7K/2/

出现此问题的原因是使用 document.getElementById()通过 ID 检索元素,该元素只能返回一个元素.因此,无论浏览器决定给您什么,您都只会得到一个.

The reason you're having this problem is that elements are retrieved by ID using document.getElementById(), which can only return one element. So you only get one, whichever the browser decides to give you.

这篇关于不能对具有相同ID的元素触发点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆