我正在从 json 文件动态生成一些带有循环的按钮,并附加 onclick 事件,该事件将一些值和数组传递给函数。
由于单击按钮时我在控制台中收到通用的“意外标识符”错误,所以有些东西不起作用;如果我用字符串或数字替换数组,则脚本可以正常工作,这意味着我传递数组的方式或数组本身一定有问题。
这就是按钮 html 输出的样子(为什么有两个 [object object]?):
<button onclick="myFunction(1,'string',{[object Object],[object Object]})">Click me</button>
生成自
var button = '<button onclick="myFunction('+otherArray.value1+',\''+otherArray.string1+'\',{'+myArray+'})">Click me</button>';
这是生成按钮之前数组在 Chrome 控制台中的样子:
(2) [{…}, {…}]
0: {param1: "1", param2: "text"}
1: {param1: "2", param2: "more text"}
length: 2
__proto__: Array(0)
有什么建议吗? 谢谢
最佳答案
您看到[object Object]
的原因是因为您如何分配onclick
,对于这些值,toString
方法将是调用,因此输出为 [object Object]
。
我可以给您的第一个建议是,在必须分配此类属性的情况下,请使用 addEventListener
,而不是以这种方式创建硬编码元素。
所以在你的情况下是这样的:
var button = document.createElement("button");
var t = document.createTextNode("Click me");
button.appendChild(t);
button.addEventListener('click', () => {
myFunction(otherArray.value1, otherArray.string1, { myArray });
});
// then append the button where you want to
关于javascript - 将 javascript 数组传递给 onclick 属性的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54468315/