javascript JQuery - 使用带有 DOMNodeInserted 的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6814219/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:56:33  来源:igfitidea点击:

JQuery - use element with DOMNodeInserted

javascriptjqueryjavascript-events

提问by CristiC

For sure this question is very easy, but I just cannot figure this out.

当然,这个问题很简单,但我就是想不通。

I'm using DOMNodeInserted event to detect when a new element is inserted.

我正在使用 DOMNodeInserted 事件来检测何时插入新元素。

I don't know how to use the current element, for example to get it's parent id.

我不知道如何使用当前元素,例如获取它的父 ID。

Now I have the function like this:

现在我有这样的功能:

document.addEventListener("DOMNodeInserted", function(event){
  var element = event.target;

  if (element.tagName == 'DIV') {
    if (element.id == 'ndiv_3-1VTSTHR') {
     alert($('#ndiv_3-1VTSTHR').parent().get(0).tagName);
    }
  }
});

This works, but it will give me the parent to ndiv_3-1VTSTHR element. I want to know the parent to any element, using JQuery.

这有效,但它会给我 ndiv_3-1VTSTHR 元素的父元素。我想知道任何元素的父元素,使用 JQuery。

I tried with

我试过

alert($(this).parent().get(0).tagName);

but with no luck.

但没有运气。

回答by Frédéric Hamidi

You probably need to initialize a jQuery object around element.target. Try:

您可能需要在 周围初始化一个 jQuery 对象element.target。尝试:

document.addEventListener("DOMNodeInserted", function(event) {
    alert($(event.target).parent()[0].tagName);
});