简体   繁体   English

查找为元素或父元素设置的onClick事件

[英]Finding onClick event if is set for the element or the parents

I want to change a HTML+JS template behavior but i don't want to re do things which are already done. 我想更改HTML + JS模板的行为,但是我不想重新做已经完成的事情。 assume we have a hierarchy of elements and looks like the inner one is calling a function on it's onclick event. 假设我们具有元素的层次结构,并且看起来内部的元素正在onclick事件上调用函数。 but when i select it on the chrome inspector console and check if it has anything for the onclick it returns null i think it's developed in a more general way or possibly on other property? 但是当我在chrome inspector控制台上选择它并检查onclick是否有任何东西时,它返回null我认为它是以更一般的方式开发的,或者可能是在其他属性上开发的?

What i want is to find that function wrap it in mine and call it after doing something else. 我想要的是找到该函数将其包装在我的容器中,并在执行其他操作后调用它。

The hierarchy is like below: 层次结构如下:

<ul> <li data-id="1234"> <div> <a href="#">the button</a> </div> </li> ... </ul>

whenever the button is pushed the data-id is sent to the server via ajax. 每当button时, data-id都会通过Ajax发送到服务器。

I hope it will work 我希望它能起作用

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
<script>
   $(document).ready(function(){
    $(".data").click(function(){
    var data = this.parentNode.parentNode.getAttribute("data-id");
    $.ajax({
    url:"url",
    data:{'data':data},
    type:"post",
    success:function((){
      });
     })
   });
});
</script>
</head>
<body>

 <li data-id="1234"> <div> <a  class="data" onclick = abc(event)>the button</a> </div>


</body>
</html>

I played a little bit with es6 and did the expected result: https://codepen.io/omgitsevan/pen/yxrVVM 我在es6上玩了一点,并达到了预期的效果: https ://codepen.io/omgitsevan/pen/yxrVVM

but basically, the code is the following: 但基本上,代码如下:

Javascript 使用Javascript

document.addEventListener('click', (evt) => {
  function getDataAttr(node, attrValue) {
    if (!node.getAttribute(attrValue)) {
      return getDataAttr(node.parentNode, attrValue)
    }

    console.log(node.getAttribute(attrValue))
  }

  getDataAttr(evt.target, 'data-id');
})

HTML HTML

<ul>
  <li data-id="1234">
    <div> <a href="#">the button</a> </div>
  </li> ... </ul>

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

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