如何正确使用.removeClass

时间:2016-06-08 05:45:21

标签: javascript jquery

var increment = 0;

$("#dial-save").click(function(){
$(".add-flow").html("");
$(".add-flow").append("<button type='button' class='btn btn-w-s btn-ivr'><i class='fa fa-hand-o-down p-xxs' aria-hidden='true'></i>Dial</button>");

    switch(increment) {
        case 0:
                $(".flow-preview").append("<div class='col-md-1'></div><div  class='col-md-1'></div><div class='col-md-10 add-flow'><button type='button' class='btn add-applet' data-toggle='modal' data-target='#myModalAddApplet'>Add Applet</button></div>");
                increment++;
                $("#myModalAppletDial").modal('hide');
                $( ".add-flow:first-child" ).removeClass("add-flow");
                break;

         case 1:
                $(".flow-preview").append("<div class='col-md-1'></div><div class='col-md-1'></div><div class='col-md-1'></div><div class='col-md-9 add-flow'><button type='button' class='btn add-applet' data-toggle='modal' data-target='#myModalAddApplet'>Add Applet</button></div>");
                increment++;
                $("#myModalAppletDial").modal('hide');
                break;

    };

});

我需要更改行$( ".add-flow:first-child" ).removeClass("add-flow");的帮助。我在这里要做的是从所有标签中删除add-flow,除了我要附加的标签...

2 个答案:

答案 0 :(得分:1)

尝试以下

switch(increment) {
            case 0:
            $('.flow-preview').find( ".add-flow" ).removeClass("add-flow");
            $(".flow-preview").append("<div class='col-md-1'></div><div class='col-md-1'></div><div class='col-md-10 add-flow'><button type='button' class='btn add-applet' data-toggle='modal' data-target='#myModalAddApplet'>Add Applet</button></div>");
            increment++;
            $("#myModalAppletDial").modal('hide');
            break;

            case 1:
            $(".flow-preview").append("<div class='col-md-1'></div><div class='col-md-1'></div><div class='col-md-1'></div><div class='col-md-9 add-flow'><button type='button' class='btn add-applet' data-toggle='modal' data-target='#myModalAddApplet'>Add Applet</button></div>");
            increment++;
            $("#myModalAppletDial").modal('hide');
            break;

};

答案 1 :(得分:0)

可能您使用:first-child 错误。正如文档所说,:first-child将选择所有父元素的第一个子元素(https://api.jquery.com/first-child-selector/)。如果你有几个.add-flow并且他们不是他们父母的第一个孩子怎么办?

我认为这是实现这一目标的简便方法:

  1. 首先,从所有标记中删除.add-flow
  2. 然后,追加新的
  3. 在您的代码中,首先 removeClass(),然后追加()

    $( ".add-flow" ).removeClass("add-flow"); // remove first, probably you dont need :first-child here
    $(".flow-preview").append("<div class='col-md-1'></div><div  class='col-md-1'></div><div class='col-md-10 add-flow'><button type='button' class='btn add-applet' data-toggle='modal' data-target='#myModalAddApplet'>Add Applet</button></div>"); // then append
    increment++;
    $("#myModalAppletDial").modal('hide');