[英]Passing parameters to a function in an onclick event
I'm trying to dynamically build some HTML and assign a function to the onclick
event of a link. 我正在尝试动态构建一些HTML并将功能分配给链接的onclick
事件。 Here's the code I've got... 这是我得到的代码...
link = document.createElement("a");
link.setAttribute("href", "#");
link.onclick = function(){someFunction(myObject.id);};
link.appendChild(document.createTextNode("Click Me!"));
My research has indicated that I wrap my function call within an anonymous function like I have done. 我的研究表明,我像过去一样将函数调用包装在匿名函数中。 What I'm finding though is that my function is called when this bit of script runs instead of on the click event. 不过,我发现的是,当脚本的这一部分运行而不是在click事件上运行时,我的函数便被调用。 This seems to be a common problem but I'm following all the advice I've found so far but to no avail. 这似乎是一个普遍的问题,但我会遵循我到目前为止发现的所有建议,但是没有用。
Any help or pointers is much appreciated. 非常感谢任何帮助或指示。
Mister B. B先生
Maybe try this alternative method: 也许尝试以下替代方法:
function someFunction(id) {
return function() {
alert(id);
};
}
link = document.createElement("a");
link.setAttribute("href", "#");
link.onclick = someFunction(myObject.id);
link.appendChild(document.createTextNode("Click Me!"));
The code you've posted works fine - I just tested it. 您发布的代码可以正常工作-我刚刚对其进行了测试。 Here are some possibilities to look for.. 这里有一些寻找的可能性。
One debugging method would be to change that line to: 一种调试方法是将该行更改为:
link.onclick = function(){alert('test'); someFunction(myObject.id);};
Is the alert popping up? 警报弹出吗? My guess is not, suggesting #1 and #2 above. 我的猜测不是,建议上面的#1和#2。 Feel free to post more code and we can look for the error elsewhere. 随时发布更多代码,我们可以在其他地方查找错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.