0

Suppose I have a Select element:

<select>
    <option value="Name 1">Simon</option>
    <option value="Name 2">Frank</option>
    <option value="Name 3">Bob</option>
    <option value="Name 4">Alex</option>
</select>

And I have an array of strings, suppose:

["Simon", "Alex"]

How do I remove from the DOM (using jQuery) every option element that does not have a inner html value contained in the above list? For example, given the above list of inner html values (["Simon", "Alex"]), I would like to remove only the <option value="Name 2">Frank</option> and <option value="Name 3">Bob</option> elements, so that the final select element would look like:

<select>
    <option value="Name 1">Simon</option>
    <option value="Name 4">Alex</option>
</select>
4

2 回答 2

7

尝试这个:

var list = ["Simon", "Alex"]; // Say your list is this

$(function(){

    $('select option').filter(function () { //Use filter on options
       return $.inArray(this.innerHTML, list) == -1 // get the option text which is not in the array
    }).remove(); //Remove them
});

演示

参考

同时,您还可以使用 ecmascript-5 规范Array.prototype.indexOf而不是 $.inArray

return list.indexOf(this.innerHTML) == -1

于 2013-06-14T02:42:18.543 回答
2

另一种方法是清除 Select 并使用数组或 JSON 格式的数据结构重新填充它:

// JSON formatted data structure
list = { "1": "Simon", "2" : "Alex" };

// Removes all options for the select box
$('select option').remove();

// Add option to the select box from list
$.each(list, function(key, value) {   
     $('select')
         .append($("<option></option>")
         .attr("value",key)
         .text(value)); 
});

上面的例子是使用 JSON fromat(我推荐它,因为它总是比数组快)。如果您仍想使用 Array,只需将 JSON 列表替换为您的数组列表(即var list = ["Simon", "Alex"];),您将获得相同的结果。

于 2013-06-14T03:06:45.933 回答