无法在具有相同ID的元素上触发click事件

问题描述:

你能帮助我理解 - 我犯了错误。我有以下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!:)

upd: Big thx to all for explanation!:)

为此使用一个类(和返回false 您的处理程序中的code>,而不是内联):

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/

您遇到此问题的原因是 ID 使用 document.getElementById(),它只能返回一个元素。所以你只能得到一个,无论浏览器决定给你什么。

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.