Javascript 将“e.target”与 jQuery 对象进行比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8606269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare 'e.target' to a jQuery object
提问by dubbelj
What I want to do:
我想做的事:
( clickedObject === someDiv ) //returns true or false
What I tried
我试过的
( $(e.target) === $('.selector') ); //returns a false negative.
My workaround
我的解决方法
( $(e.target).attr('class') === $('.selector').attr('class') ); //works as intended, not so clean though.
What is the right way to compare the object I clicked to an object in the DOM?
将我单击的对象与 DOM 中的对象进行比较的正确方法是什么?
回答by Adam Rackis
To check if e.target
has this class you can use the hasClass
function.
要检查是否e.target
有此类,您可以使用该hasClass
函数。
if ($(e.target).hasClass("selector"))
Or, if you really want to compare objects, note that jQuery selectors return a collection of items, so I think you'll want
或者,如果你真的想比较对象,请注意 jQuery 选择器返回一个项目集合,所以我想你会想要
if (e.target === $('.selector')[0])
回答by Bojangles
You're close. Use .is()
instead:
你很接近。使用.is()
来代替:
if($(e.target).is('.selector')) {
// Your code
}
The trick here is that you wrap e.target
in a jQuery object to allow it access to all the useful jQuery methods.
这里的技巧是您将e.target
jQuery 对象包装起来,以允许它访问所有有用的 jQuery 方法。
If you're just seeing whether e.target
has a certain class, try using .hasClass()
in place of .is()
:
如果您只是查看是否e.target
有某个类,请尝试使用.hasClass()
代替.is()
:
if($(e.target).hasClass('selector')) {
// Your code
}
Either method works, although .hasClass()
is a little clearer as to what the code does, and is faster than using .is()
两种方法都有效,尽管.hasClass()
代码的作用更清晰,并且比使用更快.is()
回答by Phunky
If you want to match the element that the event is attached to you can use $(this)
, or if you want to find which element triggered the event use $(event.target)
.
如果要匹配事件附加到的元素,可以使用$(this)
,或者如果要查找触发事件的元素,请使用$(event.target)
。
Below is an example of both of these.
下面是这两者的一个例子。
http://jsfiddle.net/Phunky/TbJef/
http://jsfiddle.net/Phunky/TbJef/
Unless you're using event delegation these will be the same though and if there the same element.
除非您使用事件委托,否则这些将是相同的,并且如果有相同的元素。
回答by luke
Obviously using .is()
function is the best solution here.
显然,使用.is()
函数是这里最好的解决方案。
If you find yourself doing such comparison, try to check if it is possible to use embedded jQuery mechanisms like this:
如果您发现自己在进行此类比较,请尝试检查是否可以使用像这样的嵌入式 jQuery 机制:
$(element).on("click", ".selector", function() {
alert("clicked");
});
Second argument in the .on()
method is a target selector. When using this construction (read more: http://api.jquery.com/on/#direct-and-delegated-events) there will be no need to make any additional comparisons.
该.on()
方法中的第二个参数是目标选择器。使用此构造时(阅读更多信息:http: //api.jquery.com/on/#direct-and-delegated-events)将无需进行任何额外的比较。