简体   繁体   English

如何通过调用javascript中的函数来获取两个按钮的不同值

[英]how to take two buttons diffrent value by calling function in javascript

 function getValue(){ var v = document.getElementById("btn2").value; document.getElementById("display").value += v; } 
  <input type ="text" id = "display" value = "" ></input> <tr> <td> <input type = "button" id = "btn2" value="7" onclick="getValue(this)" ></input> </td> <td> <input type = "button" id = "btn2" value="8" onclick="getValue(this)" ></input> </td> </tr> 

I just want to different value by clicking 8 or 7 button. 我只想通过单击8或7按钮获得不同的值。 but every time i got 7 as result what can i do please help.. and more i want to pass "this" in getValue(this) so that by clicking that button get the all information that buttton. 但是每次我得到7的结果时,我可以做些什么,请帮忙..还有,我想在getValue(this)中传递“ this”,以便通过单击该按钮来获取有关该按钮的所有信息。 plz help me thanks 请帮我谢谢

Your IDs, in dom should be unique. 您的ID(在dom中)应该是唯一的。 jQuery is returning only the first element when calling $('#idstring'); jQuery在调用$('#idstring')时仅返回第一个元素; as document.getElementById('#idstring') also does. 就像document.getElementById('#idstring')一样。

In this case, you could use className. 在这种情况下,您可以使用className。

You also pass a parameter to the function, but you don't use it. 您也可以将参数传递给函数,但不要使用它。

I edited this snippet to show how to bind this to the function before calling it. 我编辑了此代码片段,以显示如何在调用它之前将其绑定到该函数。 Like this, you can use 'this' if it's your thing. 这样,如果这是您的事,则可以使用“ this”。

 function getValue(el) { document.getElementById("display").value = el.value; } function getValue2() { document.getElementById("display").value = this.value; } 
 <input type="text" id="display" value=""></input> <tr> <td> <input type="button" class="btn2" value="7" onclick="getValue(this)"></input> </td> <td> <input type="button" class="btn2" value="8" onclick="getValue2.bind(this)()"></input> </td> </tr> 

  1. Make sure your ids are unique. 确保您的ID是唯一的。

  2. Make use of the argument ( this ) that you are passing. 利用您要传递的参数( this )。

 function getValue(button){ var v = document.getElementById(button.id).value; document.getElementById("display").value += v; } 
  <input type ="text" id = "display" value = "" ></input> <tr> <td> <input type = "button" id = "btn1" value="7" onclick="getValue(this)" ></input> </td> <td> <input type = "button" id = "btn2" value="8" onclick="getValue(this)" ></input> </td> </tr> 

I see you already have answers to your question. 我看到您已经有问题的答案。 However a cleared way might be to use classes. 但是,一种明确的方法可能是使用类。

$(".my_buttons").click(function(){
    $("#display").val($(this).val());
});

<input type="text" id="display" />
<input type="button" class="my_buttons" value="7" />
<input type="button" class="my_buttons" value="8" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM