如何触发 jQuery 按 HRF 进行筛选

how to trigger jquery to filter by href

本文关键字:筛选 HRF 何触发 jQuery      更新时间:2023-09-26

大家好,所以我有两个下拉选择,当用户选择第一个时,它只显示第二个选项上的选项和相应的值,但我需要做的就是将值更改为唯一值并使用第二组选项上的 href 链接这里的值 JS:

jQuery.fn.filterOn = function(selectFrom, values) {
    return this.each(function() {
        var select = this;
        var options = [];
        $(select).find('option').each(function() {
            options.push({value: $(this).val(), text: $(this).text()});
        });
        $(select).data('options', options);
        console.log(selectFrom);
        $(selectFrom).change(function() {
            var options = $(select).empty().data('options');
            var haystack = values[$(this).val()];
            console.log(haystack);
            $.each(options, function(i) {
                var option = options[i];
                if($.inArray(option.value, haystack) !== -1) {
                    $(select).append(
                    $('<option>').text(option.text).val(option.value)
                    );
                }
            });
        });            
    });
};

那么这就是选择的样子:

<select id="1" name="1">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="2" name"2">
<option href="1" value="1">1</option>
<option href="1" value="1">2</option>
<option href="1" value="1">3</option>
<option href="2" value="2">1</option>
<option href="2" value="2">2</option>
<option href="2" value="2">3</option>
</select>

我需要做的是让第二个选择根据 HREF 而不是值进行排序,我尝试了一些事情,但似乎发生的一切是其他jQuery开始播放。

就目前的情况而言,如果我在第一次选择时选择一个以 1 作为值的选项,它只会在第二个选择上显示具有相应值的选项,但我需要它来显示具有相应 href 的选项

$('select#1').on('change', function() {
  $('select#2 option[href="'+ this.value +'"]').show();
  $('select#2 option[href!="'+ this.value +'"]').hide();
});

演示

或者,在单个链中:

$('select#1').on('change', function() {
    $('select#2')
          .find('option[href="'+ this.value +'"]') // find options with selected value           
          .show() // show them
          .end()  // backtrack to select#2
          .find('option[href!="'+ this.value +'"]') // find don't match options
          .hide();  // hide unmatched options
});

演示

注意

不要只使用数字id s。