删除<选项>当自定义属性不等于x时,由.class AND执行

Remove <option> by .class AND when custom attribute NOT equal to x

本文关键字:AND 执行 class 自定义属性 选项 lt gt 删除 不等于      更新时间:2023-09-26

我所拥有的:

我有一个精选元素。有些选项同时具有类(.filterable_option(和自定义属性(data-clienturn(。

我需要什么:

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

  1. 。。。被分类为CCD_ 3
  2. 。。。具有数据自定义属性值NOT EQUAL TO预定义变量(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>

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();
    }
});

JSFiddle:

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

我的问题:

我的代码没有删除选项中所需的。什么也没发生。

您在选择器中使用了一个名称。使用id,如下所示

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

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

或者,如果你仍然想搜索名称,请尝试以下代码:

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

您有错误的选择器进行选择,并且还更正了以下位:name='myselect_b']

演示:http://jsfiddle.net/aamir/L82UH/2/

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

查看您的标记中有名称属性:

<select name="myselect_a">

并且您正在使用一个id选择器:

$('#myselect_a')

这就是问题所在。