运行Child's Onclick,但不要运行Parent's Where参数被传递

Run Child's Onclick But Not Parent's Where Argument is Passed

本文关键字:运行 参数 Where Parent Child Onclick      更新时间:2023-09-26

给出一些简单的HTML,其中一个元素有一个onclick函数,它的子元素也有一个onclick函数:

<div style='background-color:blue;width:500px;height:500px;'
    onclick='thing1();'>
    <div style='background-color:red;width:100px;height:100px;'
        onclick='thing2(57);'></div>
</div>

什么是正确的方法,以便当用户单击子元素时,只有子元素的onclick被执行,而不是父元素的,但是当父元素被单击时,它的onclick仍然被执行?我看到event.stopPropagation()将是正确的方式去,但是因为我传递一个参数给函数thing2(),我似乎不能传递事件。例如:

function thing2(a,ev) {
    // Do something with a
    ev.stopPropagation();
    }

不能工作,错误为TypeError: ev is undefined .

事件是第一个参数

function thing2(ev) {
  var a = ev.target
  ev.stopPropagation()
}

其次,最好不要使用onclick=。相反,给你的div类或id,并做这样的事情:

<div class="thing-1" data-thingy="57">
  <div class="thing-2" data-thingy="65"></div>
</div>
<script>
  $('.thing-1').click(function (ev) {
    ev.stopPropagation()
    parseInt($(ev.target).data('thingy'), 10) // 57
  })
  $('.thing-2').click(function (ev) {
    ev.stopPropagation()
    parseInt($(ev.target).data('thingy'), 10) // 65
  })
</script>

当你在click上调用一个函数时,没有事件会作为参数传递,如果你能做到这一点,那不是一个Jquery对象,也不会有stopPropagation属性。所以你需要为这两个div定义jQuery点击事件处理程序,让我们给他们id div1div2

HTML

<div id="div1" style='background-color:blue;width:500px;height:500px;'>
  <div id="div2" style='background-color:red;width:100px;height:100px;'></div>
</div>

在Javascript中,

function thing2(ev) {
  // Do something with a
  console.log(ev);
  alert('hi2');
  ev.stopPropagation();
}
function thing1(ev) {
  // Do something with a
  alert('hi1');
}
$('#div1').click(thing1);
$('#div2').click(thing2);