一个为页面上的每个元素添加 onclick 事件的小书签?
我想制作小书签,当您按下它时,页面上的所有元素都会获得一个 onclick 事件,该事件调用一个以元素作为参数或至少元素 id/class/something 的函数,这可能吗?既然如此,我该怎么办呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
点击
气泡。因此,只需绑定到并检查事件元素的
target
是什么(您需要进行一些事件规范化来绕过 IE与其他人不同。)event.target
是实际的 DOM 元素,因此您可以在此时过滤任何您想要过滤的内容。这样做的优点是,页面上有多少元素并不重要,您只需要一个事件处理程序来处理所有这些元素。 (这意味着在具有数百或数千个元素的页面上性能会更好。)
click
bubbles. So just bind to the<body>
and check what thetarget
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.)