假设我的页面上有几个按钮和 1 个文本框。
每个按钮在 JS 中调用不同的函数,但它们将相同文本框的值传递给该函数。
我需要检索一次文本框的值,将其分配给一个变量,然后从那里将变量传递给函数。因此,不要每次都写“document.getElementById('textbox1').value”来传递给函数,只需传递变量名即可。
所以而不是这个:
\<input type="button" value="button1" onclick="function**1**(document.getElementById('textbox1').value)"/>
\<input type="button" value="button1" onclick="function**2**(document.getElementById('textbox1').value)"/>
我想看这个
x = document.getElementById('textbox1').value # **THIS IS THE LINE I DON"T KNOW HOW TO DEFINE**
\<input type="button" value="button1" onclick="function**1**(x)"/>
\<input type="button" value="button1" onclick="function**2**(x)"/>
您可以使用 jQuery 的“更改”事件处理程序并获取输入值。然后将其绑定到一个变量并在任何函数中使用。您不需要将其作为参数传递,因为它已在顶部定义。你可以在函数内部引用它。
var funcParam = "";
$("#textbox1").change(function(){
funcParam = $("#textbox1").val();
});
function function1(){
console.log(funcParam)
}
function function2(){
console.log(funcParam)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<input type="text" id="textbox1"/>
<input type="button" value="button1" onclick="function1()"/>
<input type="button" value="button2" onclick="function2()"/>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句