前端,用js根据一个对象,去除另个对象中重复的元素

这里的应用场景是,两个div盛放待选项目和已选项目,如下图

  <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
                        <div class="form-group">
                            <label class="col-xs-4 control-label"><span style="color:red">  </span>待选</label>
                            <div class="col-xs-6" id="waitingSelect" style="overflow-y:auto;height:200px">
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-6 col-sm-6 col-md-6 col-lg-2">
                        @*<input type="button" id="Yd" value="->" style="color:red;margin-top:50px;width:50px;height:50px;margin-left:-20px;background-image:url(~/buttonClick.png)" />*@
                        <a href="#" id="Yd" style="color:red;margin-top:50px;width:50px;height:50px;margin-left:-60px;">
                            <img src="~/images/buttonClick.png" />
                        </a>
                        <div style="margin-top:50px">
                            <a href="#" id="MoveRest" style="color:red;margin-top:800px;width:50px;height:50px;margin-left:-60px;">
                                <img src="~/images/moveRest.png" />
                            </a>
                        </div>
                    </div>

                    <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6" style="margin-top:-136px;">
                        <div class="form-group">
                            <label class="col-xs-4 control-label"><span style="color:red">  </span>已选</label>
                            <div id="selected" class="col-xs-6" style="overflow-y:auto;height:200px">
                            </div>
                        </div>
                    </div>

  

 待选和已选项目互斥,不能重复,

我用的是这种方法去重

function Move() {
    var che = document.querySelectorAll("#waitingSelect input[type='checkbox']");
    var selected = document.getElementById("selected");
    var flag = "";
    for (var i = 0; i < che.length; i++) {
        if (che[i].checked) {
            for (var item = 0; item < selected.childNodes.length; item++) {
                if (selected.childNodes[item].childNodes[0].value == che[i].value) {
                    flag = "1";
                    break;
                }
                else
                {
                    flag = "";
                }
            }
            if (flag == "") {
                $("#selected").append("<li style='list-style-type:none'><input type='checkBox' style='' value=" + che[i].value + ">" + che[i].nextSibling.nodeValue + "</li>");
            }
        }
        //che[i].checked = false;
    }
    var checkedObj = $('#waitingSelect input:checkbox:checked');
    checkedObj.parent('li').remove();
    document.getElementById("AllCheck").checked = false;
}

  这是从待选项目移到已选项目的的按钮点击事件,用两个for循环去重,我这里是两百多个项目,性能影响不大,

但是对于数据量更大的场景来讲,可能不是那么好用,哪位大神有更好的办法,还请留言指教

猜你喜欢

转载自www.cnblogs.com/jiuyueBlog/p/11957611.html