简体   繁体   中英

Passing object as a parameter in a template literal in javascript

I currently have an object which I want to pass as a parameter to another function inside a template literal:

    var template = `<button onclick="onclick(${object})"></button>`;

However, this makes the parameter become a string value: [object Object] and doesn't pass the parameter. Is there any way to pass this parameter into the function?

Thank you very much in advance.

You are going to need to represent your object as a string. You can do this using JSON.stringify :

var template = `<button onclick="handleClick(${JSON.stringify(obj).split('"').join("&quot;")})"></button>`;

You will need to escape double quotes (which this code does), and single quotes if used for your onclick event (this code doesn't).

onclick="onclick" actually calls window.onclick - meaning that it picks up clicks anywhere. You should use a different name (such as handleClick).

I would suggest refraining from using inline event listeners for reasons like this, and because they can cause issues if you ever need to adopt a content-security-policy.

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