【问题标题】:Get form action with button named action使用名为 action 的按钮获取表单操作
【发布时间】:2014-11-12 04:51:48
【问题描述】:

背景

使用 VanillaJS 获取 HTML 表单的 action 属性值。

代码

这是代码和fiddle

<html>
<head>
  <script type='text/javascript'>
    function init() {
      alert( document.forms['form-load'].action );
    }
  </script>
</head>
<body onload="init();">
  <form name="form-load" id="form-load" action="http://google.com/q">
    <input name="query" id="query" type="text" />
    <button id="button-load" type="submit" name="action" value="load">Load</button>
  </form>
</body>
</html>

问题

对话框显示[object HTMLButtonElement],其中应为http://google.com/q(使用Firefox 32)。

问题

如何获取表单的action属性值?

更新

以下问题可能是相关的:

【问题讨论】:

    标签: javascript html forms


    【解决方案1】:

    给表单元素命名与标准表单属性或方法名称冲突是一个坏主意。例如,避免为元素指定以下名称:submitmethodactionreset

    如果必须,请改用.getAttribute() 方法获取属性值:

    function init() {
      alert( document.forms['form-load'].getAttribute("action") );
    }
    

    【讨论】:

      【解决方案2】:

      我认为用“名称”命名属性name 是一种不好的做法。为什么不改用id

      function init() {
          alert( "By ID:" document.getElementById('form-load').getAttribute('action') );
      }
      

      【讨论】:

        猜你喜欢
        • 2014-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-13
        • 1970-01-01
        • 1970-01-01
        • 2019-01-19
        相关资源
        最近更新 更多