[英]How do you select multiple elements for a javascript click event to be captured on?
I have this HTML: 我有这个HTML:
<div id="outsideContainer">
<ul>
<li>Hello</li>
<li>Goodbye</li>
</ul>
</div>
With jQuery how would I say when any of those elements is clicked execute a certain function? 使用jQuery,我怎么说呢?当单击其中任何一个元素时,执行某个功能?
I had this but it did not work: 我有这个,但是没有用:
$('#outsideContainer').click(function() {
//do stuff
});
Any ideas? 有任何想法吗?
For the most part that's fine. 在大多数情况下都可以。 Possible reasons it wouldn't work: 无效的可能原因:
You're executing your JavaScript before the "outsideContainer" element exists, eg: 您正在执行“ outsideContainer”元素之前的JavaScript,例如:
... <script> $('#outsideContainer').click(function() { //do stuff }); </script> <div id="outsideContainer"> <ul> <li>Hello</li> <li>Goodbye</li> </ul> </div>
The element must exist as of when the script is called. 从调用脚本开始,该元素必须存在。 Either just put your script
block at the very end of the page, just before the closing body
tag, or wrap your code in a function you pass into jQuery's ready
function. 您可以将script
块放在页面的最后,紧接在结束body
标签之前,或者将代码包装在传递给jQuery ready
函数的函数中。
You're expecting this
within your callback to refer to the li
element; 你期待this
您的回调中提到的li
元素; in fact, it will refer to the "outsideContainer" div
, because that's what the event handler is hooked to. 实际上,它将引用“ outsideContainer” div
,因为这是事件处理程序所依赖的。 You can get at the li
element via event.target
: 您可以通过event.target
获取li
元素:
$('#outsideContainer').click(function() { // here, this is the raw "outsideContainer" element // and event.target is the raw element that was clicked });
Note that depending on your margins and padding, event.target
might be the ul
element, if you click within the ul
but not on a li
. 请注意,如果您在ul
但未在li
上单击,则取决于您的边距和填充, event.target
可能是ul
元素。
Other things that may be worth looking at: 其他可能值得一看的东西:
This will only fire when you click on the entire div. 仅当您单击整个div时才会触发。
$('#outsideContainer').click(function() {
//do stuff
});
To capture a click on each individual li
do: 要捕捉点击每一个人li
做:
$('#outsideContainer ul li').click(function() {
//do stuff
});
As noted by TJ Crowder, what you have works, but you will want to be aware of the context of this
. 正如TJ克劳德指出,你有什么作品,但是你会想知道的情况下的this
。 Substituting event.target
for this
will give you the actual element that was clicked. 将event.target
替换为this
将为您提供被单击的实际元素。
As a demonstration, I have included below a fiddle that will alert the node (tag) type and text content of the clicked element. 作为演示,我在小提琴下方添加了一个小提琴,该提琴将警告所单击元素的节点(标签)类型和文本内容。 The <div>
, <ul>
, and <li>
s all have different colored borders to help you visually determine what you are actually clicking on. <div>
, <ul>
和<li>
都有不同的彩色边框,以帮助您直观地确定实际单击的内容。
$('outsideContainer ul li').click(function() {
//stuff
});
我没有包括实际上导致问题的javascript(它在//do stuff
,但是我遇到的问题是我正在寻找event.target只是outsideContainer而不是ul
和li
s。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.