【问题标题】:Prevent Default is not working防止默认值不起作用
【发布时间】:2015-04-15 17:03:06
【问题描述】:

我已经检查了这里,这里的这些解决方案都没有解决我的问题。 我似乎无法让 preventDefault() 工作。代码如下:

jquery:

$("#changepassword").submit(function(event) {
    event.preventDefault(); // stop normal form submission
    $.ajax({
        url: "changePassword.php",
        type: "POST",
        data: $(this).serialize(), // you also need to send the form data
        dataType: "html",
        success: function(html) {
            $("#s-window").append(html);
        }
    });
});

HTML:

    <div id="s-window">
        <form id="changepassword" action="changePassword.php" method="POST">
            <input type="password" name="currentPassword" placeholder="Current Password"/>
            <input type="password" name="newPassword" placeholder="New Password"/>
            <input type="password" name="confirmPassword" placeholder="Confirm Password"/>
            <input class="button" type="submit" value="Change Password" />
        </form>
    </div>

我的控制台上没有错误。 changePassword.php 按预期工作。但它不会更新我的#s-window,而是将我重定向到 changePassword.php 页面

如何重新编码以使页面上的所有内容都发生?

【问题讨论】:

  • 如果您仍然使用 ajax,为什么不删除 form 属性。
  • 主要是因为我不知道自己在做什么。如果可行,我可以这样做吗?你有什么可以解释我为什么要做出这些改变的吗?
  • 你为什么使用 dataType: "html"。只需将其更改为 dataType: "script it will work"。我在下面更新了我的答案。
  • 看看这个:jsfiddle.net/qpx77jj0
  • 如果在加载 dom 之前运行代码将表单与 submit 事件绑定,则代码不会执行任何操作。

标签: javascript jquery preventdefault


【解决方案1】:

您需要等到文件准备好:

$(document).ready(function(){
    $("#changepassword").submit(function(event) {
        event.preventDefault(); // stop normal form submission
        $.ajax({
            url: "changePassword2.php",
            type: "POST",
            data: $(this).serialize(), // you also need to send the form data
            dataType: "html",
            success: function(html) {
                $("#s-window").append(html);
            }
        });
    });
});

【讨论】:

    【解决方案2】:

    您可以使用return false; 尝试这种方式,如果您有任何困惑,请在此处查看更多event.preventDefault() vs. return false

    $("#changepassword").submit(function(event) {
      //event.preventDefault(); // stop normal form submission
       return false;
    });
    

    【讨论】:

    • 这仍然将我重定向到 changePassword.php 脚本。这只是一个空白的白页。
    【解决方案3】:

    至少在 IE 中,event 是一个全局变量(根据 Is 'event' a reserved word in JavaScript?)。这可能不是您的问题的原因,但是更改您的命名可能是个好主意。

    【讨论】:

    • 如果您认为这可能是问题,我可以将事件更改为 e 或其他内容?
    • 试一试。如果没有别的,它会有点整洁。 e 是个好名字。
    【解决方案4】:

    在你的 ajax 调用中将 dataType: "html" 更改为 dataType: "script"

    【讨论】:

    • 没什么区别。两者是等价的。
    • 不同的是,他使用的是提交功能,而我要求将其与 'on' 一起使用
    • api.jquery.com/submit 说:“这个方法是.on( "submit", handler )的快捷方式”
    • 我也尝试了您的解决方案。它把我重定向到我的 php 脚本页面。
    最近更新 更多