【问题标题】:JavaScript multiple forms using preventDefault not working使用 preventDefault 的 JavaScript 多个表单不起作用
【发布时间】:2014-06-11 01:07:10
【问题描述】:

我在 jQuery 文档中准备好了以下代码;

jQuery("#frmUpdateDet").submit(function (e) {
        jQuery.ajax({
            type: 'POST',
            url: './php/updateCred.php',
            data: jQuery(this).serialize(),
            async: false,
            success: function (data) {
                jQuery("#msg").empty();
                jQuery("#msg").append("<p>" + data + "</p>");
                jQuery("#msg").show().delay(800).fadeOut();
            }
        });
        e.preventDefault();
    });

    jQuery("#frmUpdatePass").submit(function (e) {
        jQuery.ajax({
            type: 'POST',
            url: './php/updateCred.php',
            data: jQuery(this).serialize(),
            async: false,
            success: function (data) {
                jQuery("#msg").empty();
                jQuery("#msg").append("<p>" + data + "</p>");
                jQuery("#msg").show().delay(800).fadeOut();
            }
        });
        e.preventDefault();
    });

但是,当我提交“frmUpdateDet”表单时,它不会重定向到我的 php 脚本,但是当我提交“frmUpdatePass”表单时,它会重定向到我的 php 脚本……这怎么可能?我的函数只是前一个函数的复制品……

edit——我的两个 HTML 表单都是通过 JavaScript 添加的,其中一个表单如下所示—— 重新编辑...我的功能

function accountSettingMenuClick($id){
// 1 = details
// 2 = security
// 3 = cloud settings

jQuery("#AD").css("text-decoration", "none");
jQuery("#AS").css("text-decoration", "none");
jQuery("#ACS").css("text-decoration", "none");

var cred;
jQuery.ajax({
    type: 'POST',
    async: false,
    url: './php/retrieve/getCred.php',
    success: function (data) {
        if (data != "null") {
            cred = JSON.parse(data);
        }
    }
});

if($id == 1) {
    jQuery("#AD").css("text-decoration", "underline");
    var adHTML;
    if(cred == "null") {
        adHTML = "<p>Error! Contact Administrator</p>";
    } else {
        adHTML = "<form id='frmUpdateDet' action='./php/updateCred.php' method='POST'><table class='table'>" +
            "<tr> <td>Name: </td> <td><input class='mainInput' name='name' type='text' value='" + cred['credentials']['name'] + "' placeholder='" + cred['credentials']['name'] + "'/></td> </tr>" +
            "<tr> <td>Surname: </td> <td><input class='mainInput' name='surname' type='text' value='" + cred['credentials']['surname'] + "' placeholder='" + cred['credentials']['surname'] + "' /></td> </tr>" +
            "</table> <table class='table'><tr><td><input type='submit' value='Update' class='mainBtn'/></td></tr></table>  </form>";
    }
    jQuery("#content").append(adHTML);
} else if ($id == 2) {
    jQuery("#AS").css("text-decoration", "underline");
    var asHTML;
    if(cred == "null") {
        asHTML = "<p>Error! Contact Administrator</p>";
    } else {
        asHTML = "<form id='frmUpdatePass' action='./php/updateCred.php' method='POST'><table class='table'>" +
            "<tr> <td>Old Password: </td> <td><input class='mainInput' name='oldPass' type='password' placeholder='Current Password' required/></td> </tr>" +
            "<tr> <td>New Password: </td> <td><input class='mainInput' name='newPass' type='password' placeholder='New Password' required onchange='form.rPass.pattern = this.value;'/></td> </tr>" +
            "<tr> <td>Re-type New Password: </td> <td><input class='mainInput' id='rPass' type='password' placeholder='Re-type New Password' /></td> </tr>" +
            "</table> <table class='table'><tr><td><input type='submit' value='Update' class='mainBtn'/></td></tr></table>  </form>";
    }
    jQuery("#content").append(asHTML);
} else if ($id == 3) {
    jQuery("#ACS").css("text-decoration", "underline");
    var acsHTML;
    if(cred == "null") {
        acsHTML = "<p>Error! Contact Administrator</p>";
    } else {
        var show;
        var limit = cred['credentials']['limit'];
        if (limit > 5000) {
            show = limit/1024;
            show = show.toFixed(2);
            show = show + " GB";
        } else {
            show = limit;
            show = show + " MB";
        }

        acsHTML = "<form id='frmUpdateUpg'><table class='table'>" +
            "<tr> <td>Current Limit: </td> <td><input type='text' class='mainInput' style='border: none; border-bottom: 1px dashed black; width: 100px; text-align: center;' disabled value='" + show +"'></td> </tr>" +
            "</table> <table class='table'><tr><td><input type='submit' class='mainBtn' value='Upgrade'/></td></tr></table>  </form>";
    }
    jQuery("#content").append(acsHTML);
}

}

还有我的角度控制器 -

function AppSettingsCtrl($scope){
if (checkSession() == false){
    location = "#/";
} else {
    validateUI();
}

accountSettingMenuClick(1);

jQuery(document).ready(function (jQuery) {
    jQuery("#AD").click(function () {
        jQuery("#content").empty();
        accountSettingMenuClick(1);
    });

    jQuery("#AS").click(function () {
        jQuery("#content").empty();
        accountSettingMenuClick(2);
    });

    jQuery("#ACS").click(function () {
        jQuery("#content").empty();
        accountSettingMenuClick(3);
    });

    jQuery("#frmUpdateDet").submit(function (e) {
        jQuery.ajax({
            type: 'POST',
            url: './php/updateCred.php',
            data: jQuery(this).serialize(),
            async: false,
            success: function (data) {
                jQuery("#msg").empty();
                jQuery("#msg").append("<p>" + data + "</p>");
                jQuery("#msg").show().delay(800).fadeOut();
            }
        });
        e.preventDefault();
    });

    jQuery("#frmUpdatePass").submit(function (e) {
        jQuery.ajax({
            type: 'POST',
            url: './php/updateCred.php',
            data: jQuery(this).serialize(),
            async: false,
            success: function (data) {
                jQuery("#msg").empty();
                jQuery("#msg").append("<p>" + data + "</p>");
                jQuery("#msg").show().delay(800).fadeOut();
            }
        });
        e.preventDefault();
    });
});

}

【问题讨论】:

  • 控制台出错?您可以发布其余的代码,包括 HTML 吗?
  • 我的控制台没有错误
  • 一般提示:如果您必须在字符串中使用 HTML(强烈建议将其存储在虚拟的 script 元素模板中),请在外部使用单引号,以便 HTML 属性可以使用标准双引号.
  • 两种表单是否都添加/放置在 处理程序代码运行之前?
  • 请同时显示第二个表单的 HTML。第一个看起来不错。

标签: javascript php jquery


【解决方案1】:

您提到您的元素是动态添加的。这通常意味着您需要使用委托事件处理程序:

例如

jQuery(document).on("submit", "#frmUpdatePass", function (e) {

委托事件在祖先处侦听,然后应用选择器,然后将函数应用到生成事件的任何匹配元素。添加处理程序时元素不需要存在。

*注意:如前所述,您确实需要使用模板而不是 HTML 字符串,或者至少切换到单引号,以便 HTML 属性将按预期被双引号当您需要有关 SO 的帮助时,您会遇到问题。

这是一个在模板中使用 HTML 字符串并使用委托事件处理程序的示例:

JSFiddle:http://jsfiddle.net/TrueBlueAussie/WpWz5/1/

追加模板的代码可以根据需要替换模板中的任何占位符字符串:

例如

 $('body').append($('#frmUpdateDettmp').html().replace("{surname}", surname).replace("{credentials}", credentials));

尽管对于多个匹配项,您需要使用带有 /g(全局)的 RegEx 表达式。

【讨论】:

  • 我以前从未使用过 Angular.. 我正在尝试 ng-view。我正在创建迷你项目来尝试不同的方式..我是如何尝试你的代码的,但它似乎没有用
  • “似乎没有工作”是不够的信息 :) 您需要填写我提供的 JSFiddle 以及您的其余代码并在那里进行测试。
  • 我对您的代码进行了一些调整,并在对委托进行了一些研究后使其工作。jQuery(document).delegate('#frmUpdateDet','submit', function (e) { });这似乎解决了我的问题:) 谢谢!
  • delegate 已过时。 on 是首选。提供的测试小提琴实际上可以正确触发,因此您可能只是在某处打错了。
  • 我正在使用我的数据库中的 JSON 对象来获取凭证 btw.. 但我已经看过有关角度文档的教程...我稍后会尝试 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-22
  • 1970-01-01
  • 2015-06-02
  • 1970-01-01
相关资源
最近更新 更多