Html 防止点击div

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

Prevent clicking through div

csshtml

提问by xPox

I have a div container, which holds several "rows" of data, with each item in the list in it's own "listRow" div. I'm using jQuery to make the "listRow" divs selectable, by toggling the css styling when clicked. Also within each row is an image div that floats on the right side of it's parent "listRow" div and contains an onclick event. When I click on the image div, the onclick event fires, but the parent "listRow" div is also clicked and "selected".

我有一个 div 容器,它包含几“行”数据,列表中的每个项目都在它自己的“listRow”div 中。我正在使用 jQuery 通过在单击时切换 css 样式来使“listRow”div 可选。在每一行中还有一个图像 div,它漂浮在它的父“listRow”div 的右侧,并包含一个 onclick 事件。当我单击图像 div 时,onclick 事件会触发,但父级“listRow”div 也被单击并“选中”。

How can I prevent from clicking through my image div?

如何防止点击我的图像 div?

pseudo html code:

伪html代码:

<div class="listContainer">
    <div class="listRow" id="listRow1">
        <div class="listItemName">List item #1</div>
        <div class="listItemIcon"><img src="images/icon.png"></div>
    </div>
    <div class="listRow" id="listRow2">
        <div class="listItemName">List item #2</div>
        <div class="listItemIcon"><img src="images/icon.png"></div>
    </div>
</div>

jQuery code:

jQuery代码:

$("div.listRow").click(function(){
    $(this).toggleClass("selected");
})

回答by dsgriffin

You'd use event.stopPropagation():

你会使用event.stopPropagation()

event.stopPropagation()- Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

event.stopPropagation()- 防止事件冒泡 DOM 树,防止任何父处理程序收到事件通知。

On the div.listItemIcon's click()event to prevent the event bubbling:

div.listItemIcon'sclick()事件上防止事件冒泡:

$('div.listItemIcon').click(function(e){
    e.stopPropagation();
});

$("div.listRow").click(function(){
   $(this).toggleClass("selected");
});

jsFiddle example here.

jsFiddle 示例在这里。

回答by Don

In the click function of the image if you grab the event and use the stopPropagation()function then it should keep the event from firing the the element's parents. eg.

在图像的点击功能中,如果您抓取事件并使用该stopPropagation()功能,那么它应该阻止事件触发元素的父元素。例如。

$('div.listItemIcon').click(function(e){
    //your code here
    e.stopPropagation();
});

回答by Luca Ziegler

Add a event parameter to the function and the following two return lines:

向函数添加一个事件参数和以下两个返回行:

$("div.listRow").click(function(e){
    if (e.target != this)
        return;
    $(this).toggleClass("selected");
});