最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery-how to detect child id? - Stack Overflow

programmeradmin2浏览0评论
<div id="first">
    <div id="here">...</div>
</div>
<div id="second">
    <div id="here">...</div>
</div>

jquery:

$("#second #here").click(function(){});

how to write jquery to detect when I click the second ?

<div id="first">
    <div id="here">...</div>
</div>
<div id="second">
    <div id="here">...</div>
</div>

jquery:

$("#second #here").click(function(){});

how to write jquery to detect when I click the second ?

Share Improve this question asked Jul 23, 2009 at 2:12 skargorskargor 1,0313 gold badges15 silver badges21 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

This is the wrong question to be asking, because you are not supposed to have duplicate IDs in a document. An ID is like the social security number of an element. You can't give multiple elements the same one, because then when you tell Javascript to find an element by ID it will be terribly confused by the fact there's more than one and give you unexpected results. The reason ID lookups are as fast as they are is because the browser can have a hash table of ID->element - violating that understanding is a bad practice, to say the least.

When you have several elements that are all of the same "type", the proper practice is to class them:

<div id="first">
    <div class="here">...</div>
</div>
<div id="second">
    <div class="here">...</div>
</div>

So then you can do:

$('#first').find('div.here');

Or:

$('div.here', '#second');

Or:

$('#first div.here');

Which would all return what you expect them to return.

This is what you are looking for, but like Paolo said, you cannot have duplicate ID's. If you're styling things, use a class.

发布评论

评论列表(0)

  1. 暂无评论