简体   繁体   English

jquery单击div中项目的事件处理程序

[英]jquery click event handler for items within a div

How do you add a jquery click event handler for a bunch of links within a div? 如何为div中的一堆链接添加jquery click事件处理程序? For example: 例如:

<div class="test">
<a href="test1.html">link 1</a>
<a href="test2.html">link 2</a>
<a href="test3.html">link 3</a>
</div>

I'd like to add a click event handler for each of the three links, so I can addClass('selected') to the link that was clicked on and removeClass('selected') from the rest. 我想为三个链接中的每一个添加一个click事件处理程序,因此我可以将addClass('selected')添加到被单击的链接和removeClass('selected')。

I know I can do them one by one, but I was wondering what the cleanest way to do this is... 我知道我可以一个接一个地做,但我想知道最干净的方法是什么......

I would use .delegate() : 我会使用.delegate()

var classname = 'selected';

$('div.test').delegate('a', 'click', function ()
{
    $(this).addClass(classname).siblings().removeClass(classname);
});

The selector will return an array of elements that match. 选择器将返回匹配的元素数组。

$('div.test a')

will be the tree links. 将是树链接。

$('div.test a').click(function() { });

Will bind to all three. 将绑定到所有三个。

Selectors work like CSS selectors, so this selects a tags inside tags with class test 选择器的工作方式与CSS选择器类似,因此选择带有类test a标签内的标签

$('.test a').click(function(){

    // select the object that was clicked on
    $(this)
        // add the selected class to it
        .addClass('selected')
        // remove the selected class from it's brothers and sisters
        .siblings().removeClass('selected')

    // stop link from loading and resetting page
    return false

})

Demo here: http://jsfiddle.net/HK6CE/ 演示: http//jsfiddle.net/HK6CE/

I would write (with no extra markup): 我会写(没有额外的标记):

$('.test a').bind('click', function() { $('。test a')。bind('click',function(){

$(this).addClass('selected').siblings().removeClass('selected'); $(本).addClass( '选择')的兄弟姐妹()removeClass( '选择')。;

}); });

Siblings() gets all the others dom elements on the same level, so it'll get all the others "a" inside .test 兄弟姐妹()将所有其他dom元素放在同一级别上,因此它会让所有其他元素“a”在内部.test

我相信它是$('.test').each(function(){})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM