问题描述
我想将参数(即字符串)传递给Onclick函数.
I would like to pass a parameter (i.e. a string) to an Onclick function.
目前,我这样做:
'<input type="button" onClick="gotoNode(' + result.name + ')" />'
其result.name例如等于字符串"Add".
with result.name for example equal to string "Add".
当我单击此按钮时,出现一个错误,提示未定义添加" .由于此函数调用可完美地与数字参数配合使用,因此我认为它与符号"有关.在字符串中.
When I click on this button, I have an error that says that "Add is not defined". Since this function call works perfectly with a numeric parameter, I assume that it has something to do with the symbols "" in the string.
如何解决此问题?
推荐答案
看起来您正在从字符串中构建DOM元素.您只需要在result.name周围添加一些引号即可:
It looks like you're building DOM elements from strings. You just need to add some quotes around result.name:
'<input type="button" onClick="gotoNode(\'' + result.name + '\')" />'
您确实应该使用适当的DOM方法来做到这一点.
You should really be doing this with proper DOM methods though.
var inputElement = document.createElement('input');
inputElement.type = "button"
inputElement.addEventListener('click', function(){
gotoNode(result.name);
});
document.body.appendChild(inputElement);
请注意,如果这是一个循环之类的事件,result
将在事件触发前发生变化,您需要创建一个额外的作用域气泡以遮盖变化的变量.
Just be aware that if this is a loop or something, result
will change before the event fires and you'd need to create an additional scope bubble to shadow the changing variable.
这篇关于在onclick函数中传递字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!