在onclick函数中传递字符串参数 [英] pass string parameter in an onclick function

查看:2479
本文介绍了在onclick函数中传递字符串参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个参数(即一个字符串)传递给一个Onclick函数。目前,我这样做:

I would like to pass a parameter (i.e. a string) to an Onclick function. For the moment, I do this:

'<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 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?

推荐答案

这看起来像是从字符串构建dom元素。你只需要在result.name中添加一些引号:

It's 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函数中传递字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆