使用jQuery来执行select追加option操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35971258/article/details/85179197

  问题:又一次见到这个select追加option,点击多次会一直追加到select下,这里提供一个很有效的方法可以解决这个常见的问题,好啦,这里就不加多说了,直接贴代码,简单直接!

  <div class="form-group">
            <label class="col-sm-3 control-label">岗位:</label>
            <div class="col-sm-8">
                <select id="post" name="post" class="form-control select2-hidden-accessible" multiple="">
                </select>

            </div>
        </div>
 function doSubmit(index, layero) {
        var tree = layero.find("iframe")[0].contentWindow.$._tree;
        if ($.tree.notAllowParents(tree)) {
            var body = layer.getChildFrame('body', index);
            $("#treeId").val(body.find('#treeId').val());
            $("#treeName").val(body.find('#treeName').val());
            console.log("treeId="+body.find('#treeId').val())

            //请求后台查询对应部门的岗位有哪些
            $.ajax({
                type: "POST",
                url: ctx + "system/post/selectPosts",
                data: {
                    "deptId": body.find('#treeId').val(),
                },
                async: false,
                error: function (request) {
                    $.modal.alertError("系统错误");
                },
                success: function (data) {
                    $("#post").empty()
                    $.each(data,function(index,item){
                        var opt=$("<option value="+item.postId+">"+item.postName+"</option>")
                        $("#post").append(opt)
                    });
                    layer.close(index);
                }
            })
            layer.close(index);
        }
    }

☛上述js中的$("#post").empty()这个方法很好用或者我们也可以将options的长度设置成为0也可以,另一种方法我这里没有贴出来,亲们自己去动手试试吧!

猜你喜欢

转载自blog.csdn.net/qq_35971258/article/details/85179197