简体   繁体   English

防止对体内所有元素进行点击动作

[英]Prevent click action on all elements inside body

I am writing a WYSWIG inline editor, all elements are editable besides editor menu elements. 我正在编写WYSWIG内联编辑器,除编辑器菜单元素外,所有元素都是可编辑的。

JS Code JS代码

$(function() {
    $("body").on("mousedown", function(e) {

        if($(e).target().is(".ignore")) {
            return;
        }

        //I hope it will stop the event to bubble up
        e.preventDefault();
        e.stopPropagation();
    });

    $("body").on("click", function(e) {
          e.preventDefault();
          e.stopPropagation();
    });
});

HTML HTML

<body>
<a href="http://google">Google</a>
<button onclick="window.location.url='https://www.amazon.com'">Amazon</button>
<button onclick="alert('Ignore unbind')" class="ignore">Ignore</button>

<iframe src="http://w3schools.org" />

Demo 演示

http://jsfiddle.net/e7gbm557/2/ http://jsfiddle.net/e7gbm557/2/

Problem 问题

In the above one, click event is prevented for the button element but if you click the anchor tag inside the iframe it takes me into the link url. 在上面的示例中,按钮元素的click事件被阻止,但是如果您在iframe中单击定位标记,则会将我带入链接网址。

Not only for anchor tags inside iframe, it happen for some other elements too. 不仅是iframe内的锚定标记,其他元素也会发生这种情况。

What is the proper way to prevent click action to all elements inside a body except some elements? 防止对除某些元素之外的体内所有元素执行单击动作的正确方法是什么?

You need to handle the click event, not the mousedown event: 您需要处理click事件,而不是mousedown事件:

$("body").on("click", function(e) {
    //I hope it will stop the event to bubble up
    e.preventDefault();
    e.stopPropagation();
});

Working JSFiddle demo . 正在运行的JSFiddle演示

Furthermore your first button element's onclick doesn't really do anything anyway. 此外,您的第一个button元素的onclick确实不会做任何事情。 Your e.preventDefault() isn't working on that, because there's simply nothing to prevent. 您的e.preventDefault()该问题,因为没有什么可以阻止的。 By default there is no url property assigned to window.location , you're simply adding this to window.location . 默认情况下,没有为window.location分配url属性,您只需将其添加到window.location This should have simply been: 这应该只是:

<button onclick="window.location='https://www.amazon.com'">Amazon</button>

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

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