我如何使用输入字段作为 javascript 函数的参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7120664/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:55:52  来源:igfitidea点击:

How can i use input fields as parameters to functions in javascript?

javascripthtmlfunctioninput

提问by Michael

So I have some input text fields and a button

所以我有一些输入文本字段和一个按钮

<input type=text value="a"/>
<input type=text value="b"/>
<input type=button onclick=???/>

and I want to use the values of those text fields as the parameters in a function that gets called when i click a button, say

我想使用这些文本字段的值作为我单击按钮时调用的函数中的参数,例如

function foo(a,b) {
    dostuff(a);
    dostuff(b);
}

I don't know what to put in the question marks. So what gets the value of the text inputs, I don't think document.getElementById gets the value of them, just the element itself.

我不知道在问号里放什么。那么什么获取文本输入的值,我不认为 document.getElementById 获取它们的值,只是元素本身。

回答by Mihai Iorga

assign an idto inputs and then call them with getElementById

分配一个id输入,然后调用它们getElementById

<input type="text" id="field1" value="a"/>
<input type="text" id="field2" value="b"/>
<input type=button onclick="foo('field1','field2');"/>

<script type="text/javascript">
    function foo(a,b) {
        elemA = document.getElementById(a).value;
        elemB = document.getElementById(b).value;
        dostuff(elemA);
        dostuff(elemB);
    }
</script>

回答by Sean Kinsey

There are multiple ways to access those values, but the recommended one is to start by giving the input elements ID's.

有多种方法可以访问这些值,但推荐的一种方法是从提供输入元素 ID 开始。

<input type=text value="a" id="a"/>
<input type=text value="b" id="b"/>

Now, you can use document.getElementByIdto get the element, and then the value

现在,您可以使用document.getElementById获取元素,然后获取值

<input type=button onclick="foo(document.getElementById('a').value,document.getElementById('b').value)" />

Note the use of ' vs " due to them being nested...

请注意 ' vs " 的使用,因为它们是嵌套的...

But you could also just pass the ID's to foo, and have foodo the getElementById-stuff.

但是您也可以将 ID 传递给foo,然后foo执行getElementById-stuff。