0

I have different divs that have an id="item". When I select one of the divs, a new class should be added to a where the div has been selected. Is there any way to do this when the IDs are not unique?

HTML:

<div class="something" id="item">
   <a href="#" class="something">...</a>
</div>
<div class="something" id="item">
   <a href="#" class="something">...</a>
</div>
<div class="something" id="item">
   <a href="#" class="something">...</a>
</div>
<div class="something" id="item">
   <a href="#" class="something">...</a>
</div>

JavaScript (what I have tried, but does not work):

// changes all links on the website
$("body").delegate('#item', 'click', function() {  
    $( "a" ).addClass( "active" );
});

Edit: I am using the delegate function because I create all the divs with PHP, otherwise the click event is not registered.

4

3 回答 3

6

永远不要有一个非唯一的 ID,那是无效的。除了无效的 ID,这不起作用,因为您使用$("a")的目标是所有链接,而不是特定链接。

HTML:

<div class="something" id="item1">
   <a href="#" class="something">...</a>
</div>
<div class="something" id="item2">
   <a href="#" class="something">...</a>
</div>
<div class="something" id="item3">
   <a href="#" class="something">...</a>
</div>
<div class="something" id="item4">
   <a href="#" class="something">...</a>
</div>

JS

// I doubt your actual site uses something in both cases,
// but I made this more explicit.
$("body").on( 'div.something', 'click', function() {  

    $('.active').removeClass( 'active' );

    // Use this to add active to div
    $( this ).addClass( "active" );

    // Use this to add active to link
    $( this ).find( 'a' ).addClass('active");

});

另请注意,我更改delegateon假设您使用的是最新版本的 jQuery - 如果没有返回delegate

于 2013-09-03T20:18:05.103 回答
1

$(this).find("a").addClass("active");

于 2013-09-03T20:18:31.057 回答
-1

你应该试试这个:

<div class="something" id="item1">
   <a href="#" class="otherthing">...</a>
</div>
<div class="something" id="item2">
   <a href="#" class="otherthing">...</a>
</div>
<div class="something" id="item3">
   <a href="#" class="otherthing">...</a>
</div>
<div class="something" id="item4">
   <a href="#" class="otherthing">...</a>
</div>



$(".something").on('click', '.otherthing', function() {  
    $(this).addClass("active");
});
于 2013-09-03T20:19:31.923 回答