简体   繁体   中英

How to pass the button value into my onclick event function?

<input type="button" value="mybutton1" onclick="dosomething()">test

当点击按钮时会引发mybutton1函数,如何将按钮mybutton1的值传递给mybutton1函数作为参数?

You can pass the value to the function using this.value , where this points to the button

<input type="button" value="mybutton1" onclick="dosomething(this.value)">

And then access that value in the function

function dosomething(val){
  console.log(val);
}

Maybe you can take a look at closure in JavaScript. Here is a working solution:

 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Test</title> </head> <body> <p class="button">Button 0</p> <p class="button">Button 1</p> <p class="button">Button 2</p> <script> var buttons = document.getElementsByClassName('button'); for (var i=0 ; i < buttons.length ; i++){ (function(index){ buttons[index].onclick = function(){ alert("I am button " + index); }; })(i) } </script> </body> </html> 

You can pass the element into the function <input type="button" value="mybutton1" onclick="dosomething(this)">test by passing this. Then in the function you can access the value like this:

function dosomething(element) {
  console.log(element.value);
}

You can get value by using id for that element in onclick function

function dosomething(){
     var buttonValue = document.getElementById('buttonId').value;
}

You can do like this.

<input type="button" value="mybutton1" onclick="dosomething(this)">

function dosomething(element){
    alert("value is "+element.value); //you can print any value like id,class,value,innerHTML etc.
};

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