【问题标题】:How to trigger two function on form submit?如何在表单提交上触发两个功能?
【发布时间】:2013-10-08 03:46:13
【问题描述】:

提交表单时我有一个表单,我将调用一个 javascript 函数并将其操作到表单处理程序。

<form action="subscribe.php" onsubmit="return form_check(this)" method="post">
<input type="text" value="">
<input type="submit" value="click">
</form>

一切正常,现在我想将相同的表单字段发送到另一个 javascript 函数,所以我在提交代码上尝试了这样的操作

    <form action="subscribe.php" 
onsubmit="return (form_check(this) & another_script(this))" method="post">

在 onsubmit 中添加了 &,但单击按钮时该功能未触发。我认为这是由于表格中的action="subscribe.php"

我还想将表单值发送到另一个 javascript 函数。我怎样才能做到这一点?

【问题讨论】:

  • 用分号分隔它们,而不是和号。如果两个函数都返回不同的东西,我不确定它会如何工作。
  • 你想返回哪个函数的值? form_checkanother_script?
  • 为什么another_script不在form_check函数内?
  • @Mike Christensen 谢谢我想同时执行这两个函数。这可能吗?
  • 这可能不是问题,但我认为您可能会混淆bitwise & operator with the logical && operator

标签: javascript jquery html


【解决方案1】:

使用 jQuery,您可以捕获表单提交。当用户尝试提交表单时,submit 事件会发送到元素。

HTML

<form id="myForm">...</form>

jQuery

$("#myForm").submit(function(event){
  event.preventDefault();

  var this = something;

  myFunctionA(this);
  myFunctionB(this);
});

var myFunctionA = function(this){
  // Function operation
}

var myFunctionB = function(this){
  // Function operation
}

【讨论】:

    【解决方案2】:

    有几个答案取决于你想要做什么。

    如果你想简单地运行这两个函数而不返回任何东西,你可以这样做:

    onsubmit="form_check(this); another_script(this);"
    

    如果你想总是运行another_script返回form_check的值,你可以这样做:

    onsubmit="another_script(this); return form_check(this);"
    

    如果你想form_check返回true时运行another_script(如果form_checkanother_script都返回true则返回true),你可以这样做:

    onsubmit="return form_check(this) && another_script(this);"
    

    但是,通常不鼓励在 onsubmit 处理程序中放入过多代码。您应该在使用 DOM 或 jQuery 之后绑定事件处理程序。

    【讨论】:

    • 你的最后一个例子等价于return (form_check(this) &amp;&amp; another_script(this)),因为&amp;&amp;是一个短路运算符,除非from_check(this)返回true,否则它不会执行another_script(this)
    • @Austin - 假设another_script 总是返回true。它可能会返回undefined,这会导致不同的行为。我会记下这一点。
    • 我还要补充一点,如果您想同时运行并检查两者,您可以执行 (form_check(this) &amp; another_script(this))? true : false!!(form_check(this) &amp; another_script(this))
    【解决方案3】:

    这行得通吗?

    onsubmit="another_script(this); return form_check(this);"
    

    当然,使用不显眼的事件处理程序总是更好。

    【讨论】:

      【解决方案4】:
      onsubmit="return ((form_check(this) + another_script(this))===2);"
      

      Demo fiddle

      【讨论】:

        猜你喜欢
        • 2018-01-15
        • 1970-01-01
        • 2015-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-06
        相关资源
        最近更新 更多