简体   繁体   English

一个元素上的多次点击事件

[英]Multiple click events on one element

http://jsfiddle.net/rHVcX/1/ http://jsfiddle.net/rHVcX/1/

Is it possible to have multiple click events on one elements, when using different selectors?使用不同的选择器时,一个元素是否可以有多个点击事件?

<button id="test" class="testclass">test</button>
<button id="test2" class="testclass2">test 2</button>

//only B
$('.testclass')[0].click(function(){alert('A');});
$('#test').click(function(){alert('B');});

// A and B
$('#test2').click(function(){alert('A2');});
$('#test2').click(function(){alert('B2');});

Yes, that's perfectly possible.是的,这是完全可能的。

However, you're misusing jQuery.但是,您误用了 jQuery。
Writing $(...)[0] gives you the first raw DOM element in the set.编写$(...)[0]会为您提供集合中的第一个原始 DOM 元素
It isn't a jQuery object, so you can't call jQuery's click method on it.它不是 jQuery object,所以不能在上面调用 jQuery 的click方法。

Instead, you should call the eq method, which returns a jQuery object containing a single element from the original set.相反,您应该调用eq方法,该方法返回一个 jQuery object ,其中包含来自原始集合的单个元素。

Change it to $('.testclass').eq(0).click(...)将其更改为$('.testclass').eq(0).click(...)

It is possible.有可能的。

However, this line:但是,这一行:

$('.testclass')[0].click(function(){alert('A');});

Will not work.不管用。 It should be:它应该是:

$('.testclass').eq(0).click(function(){alert('A');});

Indexing the jQuery object will give you the DOM element at index zero, not a filtered jQuery object.索引 jQuery object 将为您提供索引为零的 DOM 元素,而不是过滤的 jQuery ZA8CFDE6331BD59EB66AC96F8911C。

http://api.jquery.com/eq http://api.jquery.com/eq

Yes you can have multiple click events on the object.是的,您可以在 object 上进行多次点击事件。 The handlers wil be called in the order they were added (unless you say return false in one of them).处理程序将按照它们被添加的顺序被调用(除非你说在其中一个中return false )。

remove [0] or change it to .eq(0)删除[0]或将其更改为.eq(0)

<button id="test" class="testclass">test</button>
<button id="test2" class="testclass2">test 2</button>

//only B
$('.testclass').click(function(){alert('A');});
$('#test').click(function(){alert('B');});

// A and B
$('#test2').click(function(){alert('A2');});
$('#test2').click(function(){alert('B2');});

working fiddle工作小提琴

http://jsfiddle.net/rHVcX/2/ http://jsfiddle.net/rHVcX/2/

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

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