JavaScript: Adding an onClick handler without overwriting the existing one(JavaScript:添加一个 onClick 处理程序而不覆盖现有的处理程序)
问题描述
我正在尝试修改页面上的所有链接,以便在单击它们时执行一些额外的工作.
I'm trying to modify all links on a page so they perform some additional work when they are clicked.
一个简单的方法可能是这样的:
A trivial approach might be something like this:
但是一些链接已经有一个应该保留的 onClick 处理程序.我尝试了以下方法:
But some of the links already have an onClick handler that should be preserved. I tried the following:
但这不起作用,因为 oldOnClick 仅在调用处理程序时进行评估(它包含 last 链接的值作为这一点).
But this doesn't work because oldOnClick is only evaluated when the handler is called (it contains the value of the last link as this point).
推荐答案
您需要创建一个闭包来保留每个链接的原始 onclick
值:
You need to create a closure to preserve the original onclick
value of each link:
请注意,此实现仅在原始 onclick 处理程序返回 true 时执行新的 onclick 处理.如果这是您想要的,那很好,但请记住,如果您想要执行新的 onclick 处理,即使原始处理程序返回 false,您也必须稍微修改代码.
Note that this implementation only performs the new onclick handling if the original onclick handler returns true. That's fine if that's what you want, but keep in mind you'll have to modify the code slightly if you want to perform the new onclick handling even if the original handler returns false.
在 comp.lang.javascript 常见问题解答和 a href="http://www.crockford.com/javascript/private.html" rel="noreferrer">道格拉斯·克罗克福德.
这篇关于JavaScript:添加一个 onClick 处理程序而不覆盖现有的处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!