javascript - 防止默认不起作用

标签 javascript jquery preventdefault

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

J查询:

$("#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 页面

我如何重新编码才能使页面上的一切都发生?

最佳答案

您需要等到文档准备好:

$(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);
            }
        });
    });
});

关于javascript - 防止默认不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29656395/

相关文章:

javascript - get PreventDefault() - 是否可以覆盖、替换或类似的操作?

javascript - 防止在具有 routerLink 的 anchor 上导航

javascript - 逃离 preventDefault 函数

javascript - 在 RGB 颜色上创建图案

javascript - Vite - 更改 Assets 的输出目录

javascript - Proj4Leaflet 在 Leaflet 中从 4326 转换为 3857

javascript - 仅在移动设备上输入整数

javascript - 我怎样才能让我的下拉选择通过它们的值改变我的总数,但除非被选择否则不被计算

javascript - jQuery UI 最小脚本错误

javascript - 事件委托(delegate)和 jQuery load()