jquery .grep没有删除数组元素

时间:2014-03-12 07:43:21

标签: javascript jquery

$(document).ready(function () {
    var numbers = ['sachin', 'raaj', 'rahul', 'mahesh', 'sandip'];
    $('#btn').click(function ()  
  

{               var c = $(" #ad_list option:selected")。text();

        numbers = jQuery.grep(numbers, function (value) {
            return value != c;
        }); >
    });
    var option = '';
    for (i = 0; i < numbers.length; i++) {
        option += '<option value="' + i + '">' + numbers[i] + '</option>'; >
    }
    $('#ad_list').append(option);
});  

下面是显示数组

中元素的html代码下拉列表
<label>ADD:</label>               
<select name="ADD_list" id="ad_list"></select>        
<input type="submit"  id="btn" />  

1 个答案:

答案 0 :(得分:0)

删除所选元素后,您需要更新您的选项:

function updateOption(numbers) {
    $("#ad_list").empty();
    var option = '';
    for (i = 0; i < numbers.length; i++) {
        option += '<option value="' + i + '">' + numbers[i] + '</option>';
    }
    $('#ad_list').append(option);
}

$(document).ready(function () {
    var numbers = ['sachin', 'raaj', 'rahul', 'mahesh', 'sandip'];
    $('#btn').click(function () {
        var c = $("#ad_list option:selected").text();
        numbers = jQuery.grep(numbers, function (value) {
            return value != c;
        });
        updateOption(numbers);
    });
    updateOption(numbers);
});

<强> Fiddle Demo