简体   繁体   English

在 javascript 中删除 preventDefault 和 stopPropagation

[英]Removing preventDefault and stopPropagation in javascript

Hi i need to prevent the default action when the user clicked on a element and prevent its default action only for that time and need to do some other action.嗨,我需要在用户单击某个元素时阻止默认操作,并仅在该时间阻止其默认操作,并且需要执行一些其他操作。 For which i used我用过的

document.body.onclick = function (e) {
    e.preventDefault();
    e.stopPropagation();
}

But now the problem is, after i performing the above action i need to remove the preventDefault and stopPropagation , because none of the link(a href) is getting triggered after this.但现在的问题是,在执行上述操作后,我需要删除preventDefaultstopPropagation ,因为在此之后没有任何链接(a href)被触发。 So how to undo this after performing it?那么如何在执行后撤消呢? Please note that it is a pure JavaScript code and im not using any library like jquery.请注意,它是纯 JavaScript 代码,我没有使用任何像 jquery 这样的库。 So i can't use .bind and .unbind .所以我不能使用.bind.unbind Any idea on this would be greatly appreciated.对此的任何想法将不胜感激。

You can replicate the behavior of bind and unbind using addEventListener and removeEventListener您可以使用addEventListenerremoveEventListener复制bindunbind的行为

function stopIt(e) {
  e.preventDefault();
  e.stopPropagation();
}

document.body.addEventListener("click", stopIt);

// then later

document.body.removeEventListener("click", stopIt);

Note: IE <= 8 doesn't support addEventListener and removeEventListener , so you'll need to use attachEvent as mentioned here - https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener#Compatibility注意:IE <= 8 不支持addEventListenerremoveEventListener ,因此您需要使用此处提到的attachEvent - https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener#兼容性

Don't bind the event to the body, bind the event to the element you need to prevent:不要将事件绑定到正文,将事件绑定到需要防止的元素:

document.getElementById('theTarget').onclick = function(e) {
    // ...
}

If I understand your requirement correctly, I'm afraid you cannot undo the e.preventDefault();如果我正确理解您的要求,恐怕您无法撤消e.preventDefault(); . . But by default, the handler function will be executed before performing the default action.但默认情况下,处理函数将在执行默认操作之前执行。 So in your case, you just don't need the e.preventDefault();所以在你的情况下,你不需要e.preventDefault(); at all.一点也不。 And remember to attach the event listeners only to <a> tags并记住仅将事件侦听器附加到<a>标记

var aTags = document.getElementsByTagName("a");

for (var i=0;i<aTags.length;i++){
    aTags[i].onclick = function (e) {
       // just perform your action here, don't need e.preventDefault();
    }
}

Here is the working solution for breaking or rollback the stopImmediatePropagation():这是中断或回滚 stopImmediatePropagation() 的工作解决方案:

Do unbind解绑

$("#mydiv").unbind(); $("#mydiv").unbind();

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

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