删除在数组值中不存在的选择选项

时间:2014-08-21 16:46:40

标签: jquery arrays loops

我有一个动态填充的选择菜单(通过Wordpress插件),我需要删除不存在于我的数组值中的选项。

数组中的项目总是需要在我的选择菜单中。

我试图通过比较选项的文本值来做到这一点。这是我到目前为止所拥有的。一旦我介绍了数组,我就不确定如何遍历每个选项并与数组项进行比较。

jQuery("select[name*='vehicles'] > option").each(function() 
{
   var myGroups = ["Cars", "Bikes", "Airplanes", "Motorcycles"];

   jQuery.each(myGroups, function(index, value) {
      if(jQuery(this).text() != value) {
         jQuery(this).remove();
      }
   });
});

2 个答案:

答案 0 :(得分:2)

您可以尝试inArray

jQuery("select[name*='vehicles'] > option").each(function() {
  var myGroups = ["Cars", "Bikes", "Airplanes", "Motorcycles"];
  if(jQuery.inArray(jQuery(this).text(), myGroups )===-1){
  jQuery(this).remove();
  }
});

如果文本不存在,则返回-1

答案 1 :(得分:0)

按照建议使用jquery的inArray或本机JS indexOf

要在使用indexOf的情况下使代码向后兼容,您必须在未定义的位置定义它:

if(!Array.prototype.indexOf) 
{
    Array.prototype.indexOf = function(sSearchVal) 
    {
        for(var i = 0; i < this.length; i++) {
            if(this[i] === sSearchVal) {
                return i;
            }
        }
        return -1;
    };
}

并用于您的案例:

if (myGroup.indexOf(text) > -1) { /* value exists in the array */ }