繁体   English   中英

通过onclick属性将javascript数组传递给函数

[英]Passing javascript array to function from onclick property

我正在从一个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 

暂无
暂无

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

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