简体   繁体   English

如何使用jQuery获取事件目标的父级?

[英]How to get event target's parent with jQuery?

I use jQuery's event object to get the target's parent. 我使用jQuery的事件对象来获取目标的父对象。 The code is: 代码是:

event.target.parentElement

In Chrome it works, but in Firefox, it doesn't. 在Chrome中它可以工作,但在Firefox中,它没有。 I use alert() to print the output. 我使用alert()来打印输出。

event.target is an URL in both Chrome and Firefox; event.target是Chrome和Firefox中的网址; but event.target.parentElement in Chrome is [Element object], and in Firefox it is null . 但Chrome中的event.target.parentElement是[Element object],而在Firefox中它是null

What should I do to solve this problem? 我该怎么做才能解决这个问题? I still wonder if IE will have this problem? 我仍然想知道IE是否会出现这个问题?

Thanks. 谢谢。

要访问父级,您可以执行以下操作:


var par = $(event.target).parent();

To retrieve an element from an inline link's target, it may be better to use the hash attribute of target, thusly: 要从内联链接的目标中检索元素,最好使用target的hash属性,因此:

(function($) {
    parent = $(event.target.hash).parent();
})(jQuery);

And btw, instead of alert, you can get much more information using console.log with either firefox/firebug or chrome. 顺便说一下,使用console.log和firefox / firebug或chrome可以获得更多信息,而不是警报。

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

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