简体   繁体   English

event.preventDefault不能在所有地方工作吗?

[英]event.preventDefault not working everywhere?

i made a chrome extension to get element from web pages by using click event listener on content page but preventDefault is working for few times only. 我做了一个chrome扩展程序,通过在内容页面上使用click事件监听器从网页中获取元素,但preventDefault仅工作了几次。

for example on this website when i click on the menu bar it redirects to the next page instead of preventing click action to happen. 例如,在此网站上,当我单击菜单栏时,它将重定向到下一页,而不是阻止单击操作发生。 this is my event listener in content.js 这是我在content.js中的事件监听器

document.addEventListener('click', function xyz(e){
e.preventDefault();
//alert(e);
var target = e.target || event.srcElement;
var attributes = Array.prototype.slice.call(target.attributes).map(function(i)    {
    return [String(i.name)+": "+String(i.value)]
})
alert(attributes);
prompt("xpath1 :",getPathTo(target));
chrome.runtime.sendMessage({method:"captureElement",data:attributes});   
},true)

how to stop click event from occuring ! 如何停止点击事件的发生!

This is because you attach the event handler on the document itself instead of some child. 这是因为您将事件处理程序而不是某些子项附加在文档本身上。 So if you click on a child element the event will be prevented only when it will reach the document through bubbling, but in the mean time it will have been triggered. 因此,如果您单击子元素,则仅当事件通过冒泡到达文档时才会阻止该事件,但与此同时,该事件将被触发。

You either need to use return false; 您要么需要使用return false;要么使用return false; or use e.preventDefault(); 或使用e.preventDefault(); and e.stopPropagation() together. e.stopPropagation()在一起。 Because this will prevent event from bubbling up to the parent anchor tag. 因为这将防止事件冒泡到父锚标记。

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

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