簡體   English   中英

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

[英]event.preventDefault not working everywhere?

我做了一個chrome擴展程序,通過在內容頁面上使用click事件監聽器從網頁中獲取元素,但preventDefault僅工作了幾次。

例如,在此網站上,當我單擊菜單欄時,它將重定向到下一頁,而不是阻止單擊操作發生。 這是我在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)

如何停止點擊事件的發生!

這是因為您將事件處理程序而不是某些子項附加在文檔本身上。 因此,如果您單擊子元素,則僅當事件通過冒泡到達文檔時才會阻止該事件,但與此同時,該事件將被觸發。

您要么需要使用return false;要么使用return false; 或使用e.preventDefault(); e.stopPropagation()在一起。 因為這將防止事件冒泡到父錨標記。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM