简体   繁体   中英

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.

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]?):

<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:

(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] .

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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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