[英]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 您可以使用值传递给函数
this.value
,在this
指向按钮
<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. 也许你可以看看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. 你可以通过传递这个元素将元素传递给函数
<input type="button" value="mybutton1" onclick="dosomething(this)">test
。 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 您可以通过在onclick函数中使用该元素的id来获取值
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.
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.