当自定义属性NOT等于x时,按.class AND删除<option>

Cla*_*nus 11 html javascript jquery

是)我有的:

我有一个选择元素.一些选项同时具有class(.filterable_option)和custom属性(data-clienturn).

我需要的:

基于另一个元素的on change事件,我需要从select元素中删除以下选项:

  1. ......被归类为.filterable_option.
  2. ...有一个data-customattribute值不等于预定义变量(var = $some_value)的值.

我的代码:

HTML:

<select name="myselect_a">
    <option selected="selected"></option>
    <option value="Apply filter">Apply filter</option>    
</select>

<select name="myselect_b">
    <option selected="selected"></option>
    <option data-customattribute="58" value="1" class="filterable_option">Dog</option>    
    <option data-customattribute="58" value="2" class="filterable_option">Cat</option>
    <option data-customattribute="60" value="3" class="filterable_option">Parrot</option>
    <option>I have no class or custom attribute.</option>
</select>
Run Code Online (Sandbox Code Playgroud)

jQuery的:

$('#myselect_a').on('change', function() {
    var $myselect_a_option = $("#myselect_a").val();
    if($myselect_a_option === 'Apply filter'){  
        var $some_value = '58';
        $("select[name=myselect_b] option.filterable_option[data-customattribute!=" + $some_value + "]").remove();
    }
});
Run Code Online (Sandbox Code Playgroud)

的jsfiddle:

为了您的方便:http://jsfiddle.net/clarusdignus/L82UH/

我的问题:

我的代码没有删除所需的选项.什么都没发生.

Nee*_*eel 5

您在选择器中使用了一个名称.请改用ID,如下所示

<select id="myselect_a">
    <option selected="selected"></option>
    <option value="Apply filter">Apply filter</option>    
</select>
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/L82UH/1/

或者,如果您仍想使用名称,请尝试以下代码:

$('select[name="myselect_a"]').on('change', function() {
  //your code 
});
Run Code Online (Sandbox Code Playgroud)

  • 是的,不知道为什么有人向你投降.更改选择属性,或更改我猜的选择器. (2认同)