无法在具有相同ID的元素上触发click事件 [英] Can't fire click event on the elements with same id

查看:64
本文介绍了无法在具有相同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 ,而不是内联):

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/

您遇到此问题的原因是<$检索元素c $ c> 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.

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

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