替换类名在jquery中不起作用

时间:2017-05-23 05:58:26

标签: javascript jquery html

我有一个HTML段

 for (i = 0; i < 3; i++) {
        if ($("div.mm-panels").children()[i].getAttribute("id") == "m2") {
            var a = $("div.mm-panels").children()[i].getAttribute("class");
            console.log(a);
            var f = a.replace(a, "mm-panel mm-hasnavbar mm-opened");
            alert("class name chnge to : " + f);

        }
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mm-panels">
       <div class="mm-panel mm-hidden mm-hasnavbar" id="m0"></div>
       <div class="mm-panel mm-hasnavbar mm-opened" id="m1"></div>
       <div class="mm-panel mm-hidden mm-hasnavbar" id="m2"></div>
    </div>

我希望找到mm-panel的id =“m2”的子项,并用“mm-panel mm-hasnavbar mm-opened”替换类名,其他子项用“mm-panel mm”替换类名-hidden mm-hasnavbar“。

但不是替换。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

您的replace仅替换字符串“a”并将其保存为新字符串“f”。

要设置元素的类,请使用$("div.mm-panels").children()[i].setAttribute("class",f)

for (i = 0; i < 3; i++) {
        if ($("div.mm-panels").children()[i].getAttribute("id") == "m2") {
            var a = $("div.mm-panels").children()[i].getAttribute("class");
            var f = a.replace(a, "mm-panel mm-hasnavbar mm-opened");
            $("div.mm-panels").children()[i].setAttribute("class",f)
        } else {
            var a = $("div.mm-panels").children()[i].getAttribute("class");
            var f = a.replace(a, "mm-panel mm-hidden mm-hasnavbar");
            $("div.mm-panels").children()[i].setAttribute("class",f)
        }
        
        
        $("div.mm-panels").children()[i].innerText = $("div.mm-panels").children()[i].getAttribute("class")
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mm-panels">
       <div class="mm-panel mm-hidden mm-hasnavbar" id="m0"></div>
       <div class="mm-panel mm-hasnavbar mm-opened" id="m1"></div>
       <div class="mm-panel mm-hidden mm-hasnavbar" id="m2"></div>
    </div>

答案 1 :(得分:0)

当您使用jQuery标记时,可以使用.addClass()添加类,使用.removeClass()删除类。试试这个:

$("div.mm-panels").find(":not(div#md2)").removeClass("mm-panel mm-hasnavbar mm-opened").addClass("mm-panel mm-hidden mm-hasnavbar");
$("div.mm-panels").find("div#m2").removeClass("mm-panel mm-hidden mm-hasnavbar").addClass("mm-panel mm-hasnavbar mm-opened");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mm-panels">
   <div class="mm-panel mm-hidden mm-hasnavbar" id="m0">m0</div>
   <div class="mm-panel mm-hasnavbar mm-opened" id="m1">m1</div>
   <div class="mm-panel mm-hidden mm-hasnavbar" id="m2">m2</div>
</div>