A bookmarklet that adds an onclick event to every element on the page?

纵然是瞬间 提交于 2019-12-13 08:56:04

问题


I want to make bookmarklet, and when you press it all the elements on the page gets an onclick event that calls a function with the element as a parameter or at least the elements id/class/something, is that possible? In that case, how would I do it?


回答1:


click bubbles. So just bind to the <body> and check what the target of the event element is (you'll need to do a bit of event normalization to get around IE being different from everyone else.)

event.target is the actual DOM element, so you can filter on anything that you want to filter on at that point.

This has the advantage that it doesn't matter how many elements are on the page, you only need one event handler for all of them. (Which means performance will be better on pages with hundreds or thousands of elements.)




回答2:


javascript:void( document.body.onclick = function (event) { event = event || window.event; var element = event.target || event.srcElement; alert(element.textContent) } )     


来源:https://stackoverflow.com/questions/4347110/a-bookmarklet-that-adds-an-onclick-event-to-every-element-on-the-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!