简体   繁体   English

Javascript 将变量传递给 onclick 不起作用

[英]Javascript Passing variable to an onclick doesn't work

I'm trying to pass variables to another function via HTML generation using Javascript but it doesn't get through.我正在尝试使用 Javascript 通过 HTML 生成将变量传递给另一个函数,但它没有通过。 Here's my code:这是我的代码:

var wer_people_btn1 = document.createElement("span");
wer_people_btn1.setAttribute('onclick', 'SendData(' + user.ID + " ANDINFO " + susData + ')');

function SendData(reply) {
}

user.ID contains "3323"用户 ID 包含“3323”

susData contains "< DATA > (info_user)" susData 包含“< DATA > (info_user)”

The error I get:我得到的错误:

Uncaught SyntaxError: missing ) after argument list参数列表后未捕获的 SyntaxError: missing )

I think the <> brackets are causing trouble here.我认为 <> 括号在这里造成了麻烦。 How do I pass these as a string to my function?如何将这些作为字符串传递给我的函数?

Because what ever you send, that data has to be a string.因为无论你发送什么,数据都必须是一个字符串。 So string must be in quotes ' or " but it should not conflict. so make use of Javascript's both single and double quotes or try with only one by making use of escape character \\'所以字符串必须在引号'"但它不应该冲突。所以使用 Javascript 的单引号和双引号,或者通过使用转义字符\\'只尝试使用一个

wer_people_btn1.setAttribute('onclick', "SendData('" + user.ID + " ANDINFO " + susData + "')");

As mentioned in the comment, only event and element(this) can be passed.如评论中所述,只能传递事件和元素(this)。

Better workaround: The above will create a single string input for SendData, but you want to receive as separate parameters, then the following one works "SendData(" + user.ID + ",'" + susData + "')");更好的解决方法:以上将为 SendData 创建单个字符串输入,但您希望将其作为单独的参数接收,然后以下一个工作"SendData(" + user.ID + ",'" + susData + "')"); where the function prototype of SendData is SendData(userId, susData) //no quotes for user.ID since it is a number其中 SendData 的函数原型是 SendData(userId, susData) //user.ID //no quotes for user.ID since it is a number

If you need to pass custom objects, then look at this SO 1st answer , those are the only possible ways I know.如果您需要传递自定义对象,请查看这个SO 1st answer ,这是我所知道的唯一可能的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM