javascript 使用 onclick 函数传递参数时,应将其作为变量读取,而应将其作为字符串读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8940182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
passing a parameter with onclick function is read as a variable when it should be read as a string
提问by user1160409
Here is my issue:
这是我的问题:
I am creating dynamically a button with an onclick function like this:
我正在动态创建一个带有 onclick 函数的按钮,如下所示:
$("#test).html('<input type="button" value="Close" onclick="remove('+param1+','+param2+');" />');
The parameters are well read but the function is not trigger, and I've got this error message: "bob is not defined" when bob is the string value of the param1.
参数读得很好,但函数不是触发器,当 bob 是 param1 的字符串值时,我收到以下错误消息:“bob 未定义”。
Apparently it seems that bob is read as a variable when it should be read as a string, but I don't understand why.
显然,当应该将 bob 读作字符串时,它似乎被读作变量,但我不明白为什么。
Thanks much for your help!
非常感谢您的帮助!
回答by powerbuoy
That's because this string right here:
那是因为这个字符串就在这里:
'onclick="remove('+param1+','+param2+');"'
Will look like this in the end:
最终会是这个样子:
'onclick="remove(foo, bar);"'
You probably want it to look like this:
您可能希望它看起来像这样:
'onclick="remove(\'foo\', \'bar\');"'
So change it to this:
所以把它改成这样:
'onclick="remove(\''+param1+'\', \''+param2+'\');"'
You could also do this:
你也可以这样做:
$("#test").html('<input type="button" value="Close" />').find('input[type=button]').click(function () {
remove(param1, param2);
});
Edit: I also noticed that you were missing one " from your $()-call: $("#test)
should be $("#test")
.
编辑:我还注意到您在 $()-call 中遗漏了一个 " :$("#test)
应该是$("#test")
.
回答by Oybek
I can suggest you this
我可以建议你这个
<script type="text/javascript">
//<![CDATA[
var i = 0;
$(function () {
$("#lnkAdder").click(function () {
// appending new item
$("#Container").append(
$("<a>").attr({ "href": "javascript:;" }).text("Click me").click(function () {
var data = ++i;
alert("I'm clicked, I'm number " + data);
})
);
});
});
//]]>
</script>
<a href="javascript:;" id="lnkAdder">Add item</a>
<div id="Container"></div>
The key here is the javascript closure.
As you can see there a link called lnkAdder
. It is responsible to add anew item into the container. On click it appends a new item into the container. While appending you use jQuery API and create a new element, add attributes and add event listener. In the event listener body you copy the value into an internal variable. They use it as appropriate.
这里的关键是 javascript 闭包。如您所见,有一个名为lnkAdder
. 它负责向容器中添加一个新项目。单击它会将一个新项目附加到容器中。在附加时,您使用 jQuery API 并创建一个新元素,添加属性并添加事件侦听器。在事件侦听器主体中,您将值复制到内部变量中。他们会酌情使用它。