16

我有以下代码,每次用户在我的网站上提交表单时都会触发。

我想稍微修改它,以便它检查提交的操作,并根据特定关键字的存在运行一些代码。

我的代码如下:

$("form").submit(function() {
    //do some generic stuff
    var formAction = ""; //get the action of the submitted form

    if (formAction.indexOf('keyword') !== -1) {
        //do some specific stuff for these forms
    }
});         

如何获得触发此呼叫action的那个?form

4

5 回答 5

22
$("form").submit(function() {
    //some stuff...

    //get form action:
    var formAction = $(this).attr("action");

    //some other stuff...
});   
于 2013-04-18T15:26:54.460 回答
19

if you need Javascript without jQuery:

var action=document.getElementById('formId').action

with jQuery:

var action=$('#formId').attr('action');
于 2017-04-20T15:00:27.960 回答
8

在 JavaScript 中,您可以使用 getAttribute 方法:

var form = document.getElementById('register_form');
var action = form.getAttribute("action")

注意: form.getAttribute("action") 比使用 form.action 更安全。因为如果您在表单中有一个名为“action”的输入字段,那么浏览器可以返回该特定节点,而不是返回表单的操作 URL。

在此处输入图像描述

于 2019-11-14T04:34:39.327 回答
4

你可以通过这种方式获得动作属性 -

var formAction = $(this).attr("action");
于 2013-04-18T15:27:55.207 回答
2

“vanilla” JS 中,你有Element.getAttribute()
Or(如果需要)你可以使用this.action. 看下面的细微差别

document.querySelector("form").addEventListener("submit", function(e) {

  e.preventDefault(); // Prevents form from submitting
  
  console.log( this.getAttribute("action") );  // "test.php"
  console.log( this.action );                  // <address>/test.php
  
  // this.submit();  // Submit afterwards or use AJAX to construct your request

});
<form action="test.php">
  <input type="submit">
</form>

于 2018-07-31T10:56:34.493 回答