使用嵌套元素处理触摸事件

handling touch event with nested elements?

本文关键字:触摸 事件 处理 元素 嵌套      更新时间:2023-09-26

我在jquery和我的html布局方面遇到了这个问题。

例如,假设您有一个id为"#test"的div元素和一个class为"nested"的子元素img

<div id="test">
  <img class="nested" src="example.jpg">
</div>

Jquery我有两个触摸事件,

$(document).on("click", "#test", function(){
    console.log("clicked on test id");
});
$(document).on("click", ".nested", function(){
    console.log("clicked on nested element");
});

我的问题是第二次触摸事件,当用户点击嵌套项时,这也会触发第一个元素,因为很明显它是嵌套的,我不希望发生这种情况。

我很确定这是一个简单的问题,但我似乎不明白。

使用event.stopPropagation();

 $(document).on("click", "#test", function(){
    console.log("clicked on test id");
});
$(document).on("click", ".nested", function(e){
e.stopPropagation();
    console.log("clicked on nested element");
});

引用事件.stopPropagation()

您需要使用event.stopPropagation()停止传播

$(document).on("click", ".nested", function(e){
    e.stopPropagation();
    console.log("clicked on nested element");
});

在子元素click事件中使用event.stopPropagation()

event.stopPropagation():

停止将事件冒泡到父元素,防止任何父处理程序收到事件通知。添加

$(document).on("click", ".nested", function(){
     event.stopPropagation()// prevents the action without notifying the parent
    console.log("clicked on nested element");
});