繁体   English   中英

我必须单击按钮两次才能使 onclick 工作

[英]I have to click the button twice to make the onclick work

这是我的 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);
} 

提前致谢!

<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
})

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

 $('.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>

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来处理这种情况

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM