如何获取被点击子元素的onClick事件已经被触发的元素

3

我的HTML代码类似于这样:

<a onclick="customerDelete056b0d37(event)" id="ixnat-d26294a3"  data-id="dsddsss3226294a3">
  <i data-js="icons" id="it2ul" class="icons">
     <polyline points="21 8 21 21 3 21 3 8"></polyline>
     <rect x="1" y="3" width="22" height="5"></rect>
     <line x1="10" y1="12" x2="14" y2="12"></line>
  </i>
</a>

现在我想要获取任何子元素被点击时的<a>元素。

因为e.target确实返回了被点击的元素。

假设<rect x="1" y="3" width="22" height="5"></rect>被点击了,那么e.target将返回<rect x="1" y="3" width="22" height="5"></rect>

但是我想要的是与其相关联onClick的元素,就像在这种情况下一样。它将是 <a onclick="customerDelete056b0d37(event)" id="ixnat-d26294a3" data-id="dsddsss3226294a3">

这样我就可以获取此元素的data-id属性。(它也可以是其他属性,只是举例用了data-id).

而且,由于它的位置不固定,它可能是其他标签,如button,所以我不能使用closest

如何获取具有子元素点击事件处理程序的元素?

注意:没有属性或属性值将是固定的。所有都是动态的。

3个回答

6
你可以使用 currentTarget 来实现。它指向添加事件监听器的元素。

currentTarget 是 Event 接口的只读属性,标识事件在 DOM 中遍历时的当前目标。与之相对的是 Event.target, 它标识事件发生在哪个元素上,并可能是其后代元素。

文档

用法

<a onclick="customerDelete056b0d37(event)" id="ixnat-d26294a3"  data-id="dsddsss3226294a3">
    <i data-js="icons" id="it2ul" class="icons">
        <polyline points="21 8 21 21 3 21 3 8"></polyline>
        <rect x="1" y="3" width="22" height="5"></rect>
        <line x1="10" y1="12" x2="14" y2="12"></line>
    </i>
</a>

在JavaScript中

function customerDelete056b0d37(event) {
    /* This will be the a element */
    var a = event.currentTarget;

}

-5
你可以将<a>标签的id作为参数发送到函数customerDelete056b0d37("ixnat-d26294a3")中,并使用document.getElementById方法获取customerDelete056b0d37函数体内的元素。

-5

您可以使用closest方法与DOMString一起使用,例如#id.class等。像这样:

const customerDelete056b0d37 = (event) => {
  console.log(
    event.target.closest("#ixnat-d26294a3")
  );
};
<a
  onclick="customerDelete056b0d37(event)"
  id="ixnat-d26294a3"
  data-id="dsddsss3226294a3"
>
  <i data-js="icons" id="it2ul" class="icons">
    <polyline points="21 8 21 21 3 21 3 8"></polyline>
    <rect x="1" y="3" width="22" height="5"></rect>
    <line x1="10" y1="12" x2="14" y2="12"></line>
  </i>
</a>

一些其他的方法可以尝试:
1)
event.target.closest('[data-id="dsddsss3226294a3"]')
event.target.closest("[data-id]")
注意:所有提到的方法并不相同,但对于上面的示例可以起到相同的作用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接