我尝试通过以下代码来防止默认的表单提交,但是它不起作用。这是什么问题。

<div class="section-register">
    <form id="registerform" novalidate="novalidate" method="post" action="http://localhost/yify2/wp-login.php?action=register" name="registerform">
        <input id="wp-submit" class="button button-primary button-large" type="submit" value="Register" name="wp-submit">
    </form>
</div>


我的脚本是:

<script type="text/javascript">
    jQuery(document).ready(function() {
    jQuery(".section-register").find("#registerform").submit(function(event){
        if(whatever) {
            event.preventDefault();
        }
      });
   });
</script>


我也尝试通过以下代码:

<script>
jQuery(document).ready(function() {
    jQuery("#registerform").submit( function(e) {

        e.preventDefault();
    });
});
</script>

最佳答案

如果您的表单是通过AJAX请求加载的,则在将表单添加到DOM之后,您需要绑定该事件,或者在静态节点上绑定该事件:

委托事件绑定:

<script>
jQuery(function($) { // Short for jQuery(document).ready(function() {
    // Bind the event to a static node (here I use document).
    //   The closer to the dynamic node the better.
    // From your code it looks like you might be able to use
    //   $('.section-register') as the static node.
    $(document).on('submit', '#registerform', function(event) {

        event.preventDefault();
    });
});
</script>

09-20 07:31