Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

javascript - Can't fire click event on the elements with same id

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>

and the following js code (using jQuery):

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

example here

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

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!:)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...