[英]Why does the onclick function run on onclick, but not when I call it manually?
This is my code 这是我的代码
// Register onclick
var old_onclick = link.onclick;
link.onclick = function() {
astr_track_action(param);
if(typeof(old_onclick) == "function")
old_onclick();
}
And this is the html 这是HTML
<a onclick="alert('hello!');" href="http://www.google.com?acme=link&foo=bar">To google!</a>
When I click the link, the alert pops up. 当我单击链接时,弹出警报。 But when I override the onclick with my JS code, the alert does not pop up.
但是,当我用JS代码覆盖onclick时, 不会弹出警报。
Any ideas? 有任何想法吗?
Edit: I just want to add, I have debugged and confirmed that old_onclick()
is run, but no alert message shows up. 编辑:我只想添加,我已经调试并确认
old_onclick()
已运行,但是没有显示警告消息。
Edit: Here is the full code from the loop start. 编辑:这是从循环开始的完整代码。 I don't see how it's relevant, but it was requested:
我没有看到它的相关性,但有人要求:
for(var i = 0; i < document.links.length; i++)
{
var link = document.links[i];
var eventlink = link.href.split("acme=");
if(eventlink.length > 1)
{
var param = eventlink[1].split("&")[0];
var newlink = link.href;
// Register onclick
var old_onclick = link.onclick;
link.onclick = function() {
astr_track_action(param);
if(typeof(old_onclick) == "function")
old_onclick();
}
This should work as expected: 这应该可以正常工作:
example: http://www.jsfiddle.net/8RJ5y/ 示例: http : //www.jsfiddle.net/8RJ5y/
It does work, so far as I can tell: jsfiddle 据我所知,它确实有效: jsfiddle
Note that, if you are doing anything using this
, you will need to use apply
, rather than just invoking the function normally: 请注意,如果您正在使用
this
做任何事情,您将需要使用apply
,而不仅仅是正常调用该函数:
if (typeof(old_onclick) == 'function') {
old_onclick.apply(this, arguments);
}
You are creating functions in a loop. 您正在循环创建函数。
old_onclick
will point to the click handler of the last element you loop over (because upon execution, the click handlers will access old_onclick
when the loop already finished). old_onclick
将指向您循环的最后一个元素的单击处理程序(因为执行后,单击处理程序将在循环完成后访问old_onclick
)。
You have to capture the value by eg using an immediate function: 您必须通过使用立即函数来捕获值:
var old_onclick = link.onclick;
link.onclick = (function(old_onclick) {
return function() {
astr_track_action(param);
if(typeof(old_onclick) == "function")
old_onclick();
}
};
}(old_onclick));
JavaScript has no block scope, only function scope. JavaScript没有块范围,只有函数范围。 Ie
即
for(...) {
var foo = something;
}
is the same as 是相同的
var foo;
for(...) {
foo = something;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.