简体   繁体   中英

generating a button in javascript

I am using js to generate a webpage, and need to generate a button. The code is mostly working, but when I try to set the onclick attribute, I run into a problem. The onclick attribute is calling a function, and I need to give it an attribute. I have a variable in my code that contains the value I need to give to the function, but i don't know how to put this value in the parameters. If this doesn't make sense, it's probably because I'm not good at explaining things.

Basically, I have:

var potato = 5;
var btn = document.createElement(“button”);
btn.setAtribute(“onclick”, “coolFunction(potato);”);

When I open the page and go to dev view, the button looks like this:

<button onclick=“coolFunction(potato);”>this is a button</button>

However, I want the value of potato there, instead of potato itself.

Anny Ideas?

You can do this

var potato = 5;
var btn = document.createElement('button');
btn.setAttribute('onclick',`coolFunction(${potato});`); 

You could also call an anonymous function with onclick:

btn.onclick = () => coolFunction(potato)

I would forego the inline JS altogether. Add the value of potato to a data attribute on the button, and some text content, and add that to the page.

Next add an event listener to the button. When the click event on the button is fired it calls the function, and that can grab the value of the data attribute and do something with it. Here I'm just logging the value to the console.

 const potato = 5; const btn = document.createElement('button'); btn.textContent = 'Click me for potato'; btn.dataset.potato = potato; document.body.append(btn); btn.addEventListener('click', coolFunction); function coolFunction() { console.log(this.dataset.potato); }

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