【问题标题】:I have to click the button twice to make the onclick work我必须单击按钮两次才能使 onclick 工作
【发布时间】:2020-06-29 14:15:27
【问题描述】:

这是我的 html 和 JS 代码。当我第一次单击按钮时,它会提交表单但不调用 onclick 函数。我尝试在表单中添加 onsubmit 方法并使按钮类型=按钮。然而,这并没有改变什么。

表单提交是针对 Django 的。

<form action='' method='GET' required id='form_id'>

     <input class='url_box' type='url' name='url_value' placeholder='Paste the URL...'/> <br>
     <button class='submit-btn' type='submit' onclick="delayRedirect()">Listen</button>

</form>

JavaScript

function delayRedirect(){

    setTimeout(function(){
        window.location = 'player';
    }, 1500);
} 

提前致谢!

【问题讨论】:

    标签: javascript html django redirect onclick


    【解决方案1】:

    将按钮类型更改为按钮,并记录“点击”。在提交表单之前。

    $('.submit-btn').click((e) => {
      console.log('clicked.');
      $('form').submit();
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form action='' method='GET' required id='form_id'>
    
         <input class='url_box' type='url' name='url_value' placeholder='Paste the URL...'/> <br>
         <button class='submit-btn' type='button'>Listen</button>
    
    </form>

    【讨论】:

      【解决方案2】:
      <form required id='form_id'>
           <input class='url_box' type='url' name='url_value' placeholder='Paste the URL...'/> <br>
           <button class='submit-btn'>Listen</button>
      </form>
      

      /JS

      const btn = document.querySelector('.sumbit-btn')
      
      btn.addEventListener("click", (e)=>{
            e.preventDefault() // becuse the btn in <form></form> 
           // send to Django
      })
      

      【讨论】:

        【解决方案3】:

        HTML

        <form action='' target="you_dont_see_me" method='POST' required id='form_id'>
        
             <input class='url_box' type='url' name='url_value' placeholder='Paste the URL...'/> <br>
             <button class='submit-btn' type='button' onclick="delayRedirect()">Listen</button>
        
        </form>
        <iframe name="you_dont_see_me" style="display:none"></iframe>
        

        JS

        function delayRedirect(){
                document.getElementById('form_id').submit();
            setTimeout(function(){
                //do whatever you want
            }, 1500);
        } 
        

        您可以使用 iframe,但您的方法需要更改为 POST。 我个人会使用ajax来处理这种情况

        【讨论】:

        • 这是一个很好的解决方案,但问题是我需要先提交表单,然后延迟重定向,因为 Django 在后台进行了某种转换。
        • 我尝试了您的 JavaScript 函数,但我仍然需要再单击一次按钮才能使超时起作用。第一次单击仅提交表单。这真的很奇怪。
        猜你喜欢
        • 1970-01-01
        • 2012-10-01
        • 1970-01-01
        • 2015-07-02
        • 2021-12-30
        • 2013-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多