Javascript 使用javascript的按钮值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3439247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
value of button using javascript
提问by Lalchand
I have 3 buttons in my form.
我的表单中有 3 个按钮。
All the button actions goes to a same page after clicking it depending upon what button is clicked.
单击后,所有按钮操作都会转到同一页面,具体取决于单击的按钮。
My query is: The name of the buttons are 'add','edit' and 'remove'
我的查询是:按钮的名称是“添加”、“编辑”和“删除”
When the 'add' button is clicked, using js I need to get the value of that button and similarly for the other two buttons....
单击“添加”按钮时,使用 js 我需要获取该按钮的值,其他两个按钮的值也类似....
Can you please help?
你能帮忙吗?
回答by cHao
<form>
<script type="text/javascript">
function doAction(value)
{
// Don't really have anything to set...just show the value
alert(value);
}
</script>
<input type="button" value="Add" onclick="doAction(this.value)">
<input type="button" value="Edit" onclick="doAction(this.value)">
<input type="button" value="Remove" onclick="doAction(this.value)">
</form>
There are other ways that involve not even passing the button's value, but they're not as compatible across browsers (IE uses a slightly different event model).
还有其他方法甚至不涉及传递按钮的值,但它们在浏览器之间的兼容性并不好(IE 使用的事件模型略有不同)。
Of course, if you can get by without doing it in Javascript, and can just pass the clicked button to the server, it gets even easier than that...
当然,如果你不用 Javascript 就可以通过,并且可以将点击的按钮传递给服务器,它会变得更容易......
<form>
<input type="submit" name="action" value="Add">
<input type="submit" name="action" value="Edit">
<input type="submit" name="action" value="Remove">
</form>
and whichever button you click gets put into the url as action=Addor whatever.
并且您单击的任何按钮都会作为action=Add或其他方式放入网址。
回答by ?ukaszW.pl
What about:
关于什么:
var buttonValue = document.getElementById('IdOfYourButton').value
回答by yogesh kumar
There is target property which you can use.It targets the element which caused the event to occur.
您可以使用 target 属性。它针对导致事件发生的元素。
button.addEventListener('click',function(e){
console.log(e.target.value);
});
回答by aniri
have you tried: document.getElementById('button_id').valuein the js function that you'll call when the button is clicked?
您是否尝试过:document.getElementById('button_id').value在单击按钮时将调用的 js 函数中?

