我編寫了一個代碼,將點擊事件添加到帶有js的頁面中的所有標記。在點擊事件中獲取所有標記名稱
function modifyText(obj) {
console.log(obj.target.tagName);
}
var el = document.body.getElementsByTagName("*");
console.log(el);
for (var i=0 ;i<el.length; i++){
el[i].addEventListener("click", modifyText, false);
}
在modifyText
函數我想要得到任何標籤點擊它。 例如,在這個網站
<div>
<h3>
<b>salaaaaam<i> this is a test</i> </b>for add a click event to all tags in pages.
</h3>
</div>
我想打印 「I,B,H3,DIV」 當點擊
這是一個測試
,但我得到的東西像這個「我,我,我,我」。
任何人可以幫助嗎? 謝謝。
use var el = document.querySelectorAll(「*」); https://jsfiddle.net/1rch163p/6/ – jeff
將'obj.target.tagName'改爲'this.tagName' - 'this'將引用冒泡順序中的當前元素,而'target'將始終引用始發元素。 – BatScream
不,這是不同的。 @Endless –