简体   繁体   English

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

[英]Passing javascript array to function from onclick property

i'm dynamically generating some buttons with a loop from a json file with an onclick event attached that passes some values and an array to a function. 我正在从一个json文件动态地生成一些带有循环的按钮,并带有一个onclick事件,该事件将一些值和一个数组传递给函数。

Something doesn't work since i get a generic "unexpected identifier" error in the console when clicking the button; 某些操作不起作用,因为单击按钮时在控制台中出现通用的“意外标识符”错误; if i replace the array with a string or a number the script works meaning that there must be something wrong in my way of passing the array or in the array itself. 如果我用字符串或数字替换数组,脚本将起作用,这意味着在传递数组或数组本身的方式中一定存在错误。

This is what the buttons html output looks like (why are there two [object object]?): 这是html输出的按钮外观(为什么有两个[object object]?):

<button onclick="myFunction(1,'string',{[object Object],[object Object]})">Click me</button>

Generated from 产生于

var button = '<button onclick="myFunction('+otherArray.value1+',\''+otherArray.string1+'\',{'+myArray+'})">Click me</button>';

This is what the array looks like in chrome console just before generating the buttons: 这是在生成按钮之前数组在chrome控制台中的外观:

(2) [{…}, {…}]
0: {param1: "1", param2: "text"}
1: {param1: "2", param2: "more text"}
length: 2
__proto__: Array(0)

Any suggestions? 有什么建议么? Thanks 谢谢

The reason because you see [object Object] is because for how you assign the onclick , for those values the toString method will be called, so the output is [object Object] . 之所以看到[object Object]是因为分配onclick ,对于这些值,将调用toString方法,因此输出为[object Object]

First suggestion I could give you, is that in these cases where you have to assign such attributes, use addEventListener , rather than creating the hardcoded element in this way. 我可以给您的第一个建议是,在这些情况下,您必须分配此类属性,请使用addEventListener ,而不是以这种方式创建硬编码的元素。

So in your case something like: 因此,在您的情况下,例如:

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