AddClass和RemoveClass恢复为原始版本

时间:2016-09-20 07:22:21

标签: jquery

我一直在研究这个问题,并一直在寻找解决方案。

背景 我想删除“customBox disabled”类并添加类“customBox”。我尝试了几种方法; .removeClass(“customBox disabled”)。addClass(“customBox”),toggle(....,....)以及下面但无济于事。问题是代码确实已经改为新类,但是一旦程序结束就会恢复。但为什么?有专家吗?

$(document).on("click", "#btnStep2", function() {

    alert($("#step2").children().children().children().children().eq(1).children().eq(1).attr("class"));
    if ($("#step2").children().children().children().children().eq(1).children().children().is(':disabled')) {
        alert("disabled");
        if ($("#step2").children().children().children().children().eq(1).children().eq(1).hasClass("customBox disabled")) {
            $("#step2").children().children().children().children().eq(1).children().eq(1).removeClass();
            alert($("#step2").children().children().children().children().eq(1).children().eq(1).attr("class"));
            $("#step2").children().children().children().children().eq(1).children().eq(1).addClass("customBox disabled");
            alert($("#step2").children().children().children().children().eq(1).children().eq(1).attr("class"));
            return false;
        }
    } else {
        alert("enabled");
        if ($("#step2").children().children().children().children().eq(1).children().eq(1).hasClass("customBox")) {
            $("#step2").children().children().children().children().eq(1).children().eq(1).removeClass();
            alert($("#step2").children().children().children().children().eq(1).children().eq(1).attr("class"));
            $("#step2").children().children().children().children().eq(1).children().eq(1).addClass("customBox");
            alert($("#step2").children().children().children().children().eq(1).children().eq(1).attr("class"));
            return false;
        }
    }
    return false;
});

2 个答案:

答案 0 :(得分:0)

首先,您需要替换所有这些.children方法。只需使用find()方法使代码更清晰,更易于阅读。

其次,我想向您清楚“禁用”和“customBox”是两个独立的类。通过查看您的问题的描述,您只想切换“禁用”类。 “customBox”类不需要做任何事情。

毕竟这个尝试下面的代码。希望有所帮助

$(document).on("click", "#btnStep2", function() {
    var custom_box = $("#step2").find(".customBox");
    if (custom_box.length > 0){
        custom_box.toggleClass("disabled");
    }
});

快乐编码:)

答案 1 :(得分:0)

当我将以下代码粘贴在顶部时,问题就解决了。谢谢大家的帮助。真的很感激。

   Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function (evt, args) {
相关问题