【问题标题】:how to change the action of submit button after submission提交后如何更改提交按钮的动作
【发布时间】:2017-10-12 00:38:56
【问题描述】:

我想在用户登录后将提交按钮更改为调用注销功能


<html>
<head>
 /* Here I have the links for jQuery and bootstrap so, they are working properly
</head>
<body>
<form onsubmit="signIn(event)">
<input type="text" id="username" />
<input type="password" id="password" />
<input type="submit" id="connect_disconnect">
</form>
</body>

<script type="text/javascript">
  function signIn() {
    code ....
    // Below I just change the caption of the submit button from 'Connect' to 
    // 'Disconnect'
    $("#connect_disconnect").text('Disconnect');
    }
</script>

<script type="text/javascript">
  function signOut() {
    code...
    }
</script>

</html>

使用上面的代码,当我点击提交按钮时,即使我已经登录它也会调用signIn函数。我希望它在我已经签名时调用signOut函数。有任何想法吗? 提前感谢,如果我的问题不清楚,请告诉我。

【问题讨论】:

    标签: javascript jquery html forms events


    【解决方案1】:

    如果您将“提交”事件处理程序应用于您的表单,然后运行event.preventDefault(),您可以阻止表单以本机方式提交,并且您可以运行任何您想要的 Javascript。

    下面我添加了一个代码示例,展示了您可以采取哪些措施来捕获事件。

    我尽量不在我的答案中添加太多哲学,但我决定包含一个链接的 Javascript 文件的示例。


    HTML

    <body>
      <form id="theForm">
        <input type="text" id="username" />
        <input type="password" id="password" />
        <input type="submit" id="connect_disconnect">
      </form>
      <script type="text/javascript" src="/script.js"></script>
    </body>
    

    Javascript (script.js)

    (function() { // Create closure to avoid global-scoped variables
    
      var theForm = document.getElementById('theForm'); // Select the <form> element
    
      theForm.addEventListener('submit', handleFormSubmission); // Bind event listener.
    
      function handleFormSubmission(event) {
        event.preventDefault(); // Keep the form from taking any further native action
    
        if( /* user is signed in */ )
          signOut();
        else
          signIn();
      }
    
      function signIn() {
        // Sign In Code
      }
    
      function signOut() {
        // Sign Out Code
      }
    
    })(); // End closure
    

    【讨论】:

    • 太棒了!乐意效劳。随意“选择”这个作为答案,因为它对你有用。
    • 当然,但是,在哪里选择答案导致我找不到它。再次感谢
    • 这很狡猾。看起来你找到了。谢谢!
    猜你喜欢
    • 2014-05-03
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    相关资源
    最近更新 更多