【问题标题】:Handle multiple forms behavior with a single javascript function使用单个 javascript 函数处理多个表单行为
【发布时间】:2018-02-13 12:52:03
【问题描述】:

我有 3 个不同的 HTML 页面,其中包含一个表单。
除了 id 属性(和一些子 id 属性)之外,所有表单看起来都相同,尽管每个表单的 Javascript 行为应该相同。

我想在某个操作上调用相同的 Javascript 函数,但必须确定从哪个表单触发了该操作,以便该函数知道应该执行其主体的哪个部分。

form1.html

<form id="form1">
 <input id="fname1"/>
 <input type="submit" id="btn-sub" onclick="fun()"/>
 <p id="demo"></p>
</form>

form2.html

 <form id="form2">
 <input id="fname2"/>
 <input type="submit" id="btn-sub" onclick="fun()"/>
 <p id="demo"></p>
 </form>

form3.html

 <form id="form3">
 <input id="fname3"/>
 <input type="submit" id="btn-sub" onclick="fun()"/>
 <p id="demo"></p>
 </form>

javascript函数

function fun() {
    // Here I would like conditions to look like
    if ( /* function call from form1 id then */ ) {
        document.getElementById("demo").innerHTML = "Hello form 1";
    }
    if ( /* function call from form2 id then */)  {
        document.getElementById("demo").innerHTML = "Hello form 2";
    }
    if ( /* function call from form3 id then */) {
        document.getElementById("demo").innerHTML = "Hello form 3";
    }
 }

【问题讨论】:

  • 您可以将不同的参数传递给 fun() 并在此基础上为 if...添加条件...
  • 如何将当前表单 ID 作为参数发送给 javascript 函数
  • 格式化,改写。

标签: javascript html


【解决方案1】:
function fun()
     {

     var formID = $(this).closest("form").attr("id");
     //here i want conditions like
     if(formID==your Condition1)
     {
     document.getElementById("demo").innerHTML="Hello form 1";
     }
     if(formID==your Condition2)
     {
     document.getElementById("demo").innerHTML="Hello form 2";
     }
     if(formID==your Condition2)
     {
     document.getElementById("demo").innerHTML="Hello form 3";
     }
     }

【讨论】:

  • var formID = $(this).closest("form").attr("id");它在 y javascript 函数中不起作用。我可以在 javascript 函数的 .js 文件中使用它吗
【解决方案2】:

您将从提交按钮中删除 onclick 功能。

您将像这样使用 jquery 事件处理程序:-

$(function () {
        $('form').on('submit', function (event) {
            switch(event.target.id)
                 case 'form1':
                 // Do Some Code
                 break;

                 case 'form2':
                 // Do Some Code
                 break;                     
        });
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2020-11-07
    相关资源
    最近更新 更多