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

Mic*_*ael 6 html javascript input function

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

<input type=text value="a"/>
<input type=text value="b"/>
<input type=button onclick=???/>
Run Code Online (Sandbox Code Playgroud)

我希望使用这些文本字段的值作为单击按钮时调用的函数中的参数,比方说

function foo(a,b) {
    dostuff(a);
    dostuff(b);
}
Run Code Online (Sandbox Code Playgroud)

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

Mih*_*rga 7

分配一个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>
Run Code Online (Sandbox Code Playgroud)


Sea*_*sey 7

有多种方法可以访问这些值,但推荐的方法是首先给出输入元素ID.

<input type=text value="a" id="a"/>
<input type=text value="b" id="b"/>
Run Code Online (Sandbox Code Playgroud)

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

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

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

但你也可以把ID传递给foo,并且foo做了getElementById-stuff.