【问题标题】:javascript passing text input to a onclick handlerjavascript将文本输入传递给onclick处理程序
【发布时间】:2011-09-15 07:04:35
【问题描述】:

假设我有一个如下表格。如何将名为“configname”的文本框中的值传递给 onclick 函数处理程序??

<form id="loadconfigform">
        Config Name: <input type="text" name="configname" />
        <input type="button" value="Submit" onclick="onLoadConfigPress(configname)" />
    </form>

【问题讨论】:

    标签: javascript html onclick


    【解决方案1】:

    给输入字段一个id

    <input type="text" id="configname" name="configname" />
    

    现在修改点击处理程序如下:

    <input type="button" value="Submit" 
      onclick="onLoadConfigPress(document.getElementById('configname').value)" />
    

    或者如果您在该页面上只有一个表单,您也可以使用forms 数组:

    <input type="button" value="Submit" 
      onclick="onLoadConfigPress(document.forms[0].configname.value)" />
    

    【讨论】:

      【解决方案2】:
      <form id="loadconfigform">
         Config Name: <input type="text" id="configname" name="configname" />
         <input type="button" value="Submit"
           onclick="onLoadConfigPress(document.getElementById('configname').value);" />
      </form>
      

      【讨论】:

      • @user...... id 必须是元素的唯一标识符。 document.getElementById(...) 快速查找并返回指向元素的指针。
      【解决方案3】:
      <form id="loadconfigform">
              Config Name: <input type="text" name="configname" />
              <input type="button" value="Submit" onclick="onLoadConfigPress(document.getElementsByName('configname')[0].value)" />
          </form>
      

      只需用它的名字来称呼它。不过我建议使用 ID。

      如果您有其他同名元素,这将不起作用,因此请像其他答案建议的那样使用 ID。

      【讨论】:

      • 这行不通。 name 不是唯一的,您必须切换到使用document.getElementById('loadconfigform').getElementsByName(...)[0],因为其他元素可以具有相同的name 属性并且可以放在我们的元素之前
      • 类似地,其他元素也可以被赋予不同的名称,但在实践中,我还没有看到这种情况发生。不过,我知道他应该使用身份证。我只是在这里给他一个解决他的具体问题的方法。
      • 你对他的具体问题的解决方案并不总是有效。你必须在回答中写下这个。
      【解决方案4】:

      这是一个古老的问题 - 但不知何故我到了这里。

      所以,“这个”这个神奇的词在这里是你的朋友。 'this' 是被点击的元素,它将包含元素的值。所以

      <form id="loadconfigform">
          Config Name: <input type="text" name="configname" />
          <input type="button" value="Submit" onclick="onLoadConfigPress(this)" />
      </form>
      
      function onLoadConfigPress(el){
      
          var configName = el.value;
          // do other things
          // . . .
      }
      

      附注:如果您想将原始事件与“this”一起传递,请将其作为魔术字“event”作为第一个参数包含在内。

      onclick="onLoadConfigPress(event,this)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-03
        • 1970-01-01
        • 2012-11-05
        • 1970-01-01
        • 1970-01-01
        • 2017-07-01
        • 1970-01-01
        相关资源
        最近更新 更多