【问题标题】:get an instance of the form being submitted in javascript获取在 javascript 中提交的表单实例
【发布时间】:2010-07-01 17:05:49
【问题描述】:

我想在提交之前处理正在提交的表单。

  1. 页面中可能有多个表单
  2. 我不知道表单名称/id

原因:我想在模板级别提交表单之前进行一些调整。

【问题讨论】:

  • 你在使用某种 JS 框架(jQuery、Prototype、MooTools)吗?

标签: javascript forms hidden-field onsubmit


【解决方案1】:

如果没有 jQuery,它会是这样的:

for (var i=0; i < document.forms.length; i++){
  document.forms[i].onSubmit = function(){
    // logic goes here;
    // document.forms[i] is the instance of form
    if (formIsHappy()){
      return true; //form submits
    }else{
      return false; //prevents the submit
    }
  };
}

【讨论】:

    【解决方案2】:

    使用 jQuery 会是这样的:

    $(function() {
      $('form').submit(function() {
        // the code goes here;
        // variable `this` is an instance of form
        alert($(this).className);
      });
    });
    

    【讨论】:

      【解决方案3】:

      如果你使用 jQuery,你可以看看做这样的事情:

      $("form").submit(function(e) {
          console.log("Form ID that is being submit %s",$(this).attr("id"));
      });
      

      在纯 javascript 中,您可以通过执行 document.getElementsByTagName("form") 并遍历您获得的数组来实现类似的操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-10
        • 2013-11-07
        相关资源
        最近更新 更多