Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

javascript - 在onclick函数中传递字符串参数(pass string parameter in an onclick function)

I would like to pass a parameter (ie a string) to an Onclick function.(我想将参数(即字符串)传递给Onclick函数。)

For the moment, I do this:(目前,我这样做:)
'<input type="button" onClick="gotoNode(' + result.name + ')" />'

with result.name for example equal to string "Add".(例如,result.name等于字符串“ Add”。)

When I click on this button, I have an error that says that Add is not defined.(当我单击此按钮时,出现一个错误,提示未定义添加。) Since this functioncall works perfect with a numeric parameter, I assume that it has something to do with the symbols "" in the string.(由于此函数调用可以完美地与数字参数一起使用,因此我认为它与字符串中的符号“”有关。) Did anyone had this problem before?(以前有人遇到过这个问题吗?)   ask by JasperTack translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like you're building DOM elements from strings.(看起来您是从字符串构建DOM元素。)

You just need to add some quotes around result.name:(您只需要在result.name周围添加一些引号即可:)
'<input type="button" onClick="gotoNode('' + result.name + '')" />'

You should really be doing this with proper DOM methods though.(您实际上应该使用适当的DOM方法来执行此操作。)

var inputElement = document.createElement('input');
inputElement.type = "button"
inputElement.addEventListener('click', function(){
    gotoNode(result.name);
});

?document.body.appendChild(inputElement);?

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.(请注意,如果这是一个循环之类的东西, result将在事件触发前发生变化,您需要创建一个额外的作用域气泡以遮盖变化的变量。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...