admin管理员组文章数量:1428481
/
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');});
http://jsfiddle/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');});
Share
Improve this question
asked Aug 12, 2011 at 14:32
Björn RådströmBjörn Rådström
231 silver badge3 bronze badges
1
-
$('.testclass')[0]
will give you the DOM element, not a jQuery object. It should be$('.testclass').eq(0)
or just$('.testclass')
. – Felix Kling Commented Aug 12, 2011 at 14:35
4 Answers
Reset to default 4Yes, that's perfectly possible.
However, you're misusing jQuery.
Writing $(...)[0]
gives you the first raw DOM element in the set.
It isn't a jQuery object, so you can't call jQuery's click
method on it.
Instead, you should call the eq
method, which returns a jQuery object containing a single element from the original set.
Change it to $('.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.
http://api.jquery./eq
Yes you can have multiple click events on the object. The handlers wil be called in the order they were added (unless you say return false
in one of them).
remove [0]
or change it to .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/rHVcX/2/
本文标签: javascriptMultiple click events on one elementStack Overflow
版权声明:本文标题:javascript - Multiple click events on one element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745412424a2657530.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论