[英]jQuery preventDefault onclick function
I have this simple jQuery script that asks to confirm action when you click on a link.我有这个简单的 jQuery 脚本,当您单击链接时会要求确认操作。 And it works great when it's a normal
a href
link, but I have onclick
script assigned to the button and it does not prevent it from firing.当它是一个普通
a href
链接时它工作得很好,但我有onclick
脚本分配给按钮,它不会阻止它触发。 I need it to prevent it only once.我只需要它来防止它一次。 How can I achieve that?
我怎样才能做到这一点?
$(".mybutton").one('click', function() { event.preventDefault(); $(this).html("Are you sure?"); }); function test() { $(".forthebutton").html("button click function worked"); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="mybutton" onclick="test();">Button</button> <br /><br /><br /> <span class="forthebutton">button click should change this text</span>
You need to remove original onclick
and give it back in this case because you can't influent on onclick
handler.您需要删除原始
onclick
并在这种情况下将其归还,因为您无法影响onclick
处理程序。
const btn = $(".mybutton"); const onclick = btn.prop('onclick'); // save onclick fn btn.prop('onclick', null); // remove onclick from button btn.one('click', function() { $(this).html("Are you sure?"); btn.on('click', onclick); // add onclick back to button }); function test() { $(".forthebutton").html("button click function worked"); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="mybutton" onclick="test();">Button</button> <br /><br /><br /> <span class="forthebutton">button click should change this text</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.