将文本框值分配给 HTML Body 中的变量并传递给多个函数

Assign a textbox value to a variable in HTML Body and pass to several functions

假设我的页面上有几个按钮和 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>