How can I add a variable to a jquery selector of a pseudo-class?

泄露秘密 提交于 2020-01-03 05:20:12

问题


is it possible to add a variable to a jquery string selector of a pseudo-element? I've tried both codes below but none has seen to work, could you please assist me?

   $(function () {
    $("option").click(function(){
    var filt1 = $(this).attr('id');
 $("#filter2 option[class!=filt1]").hide();
  $("#filter2 option[id*=filt1]").show();
});
});

and

 $(function () {
        $("option").click(function(){
        var filt1 = $(this).attr('id');
     $('#filter2 option[class!='+ filt1+ ']').hide();
      $('#filter2 option[id*='+ filt1+']').show();
    });
    });

回答1:


Events and hide are not supported on <option> cross browser! Remove and append based on values in first select

First store and remove the <option>s in #filter2.

Change to using the value on options in filter1 and use the change event of the <select>.

Then when a change is made...clone and filter the stored <option> and put the filtered ones only into #filter2

var $filter2 = $('#filter2'),
  // store options for #filter2
  $filter2Opts = $filter2.children().detach();

$('#filter1').change(function() {    
  var $newOpts = $filter2Opts.clone().filter('.' + $(this).val())
  $filter2.html($newOpts);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple size="2" id="filter1">
  <option value="opt1">I'm option 1</option>
  <option value="opt2"> I'm option 2</option>
</select>

<select multiple size="4" id="filter2">
  <option class="opt1"> I'm option 1 sub-option A</option>
  <option class="opt1"> I'm option 1 sub-option B</option>
  <option class="opt2"> I'm option 2 sub-option A</option>
  <option class="opt2"> I'm option 2 sub-option B</option>
</select>



回答2:


Your second try is close, you're just missing quotes around your attribute value:

$(function () {
   $("option").click(function(){
      var filt1 = $(this).attr('id');
      $('#filter2 option[class!="'+ filt1+ '"]').hide();
      $('#filter2 option[id*="'+ filt1+'"]').show();
   });
});

But if I understand what you're trying to do correctly, you may want this:

$(function () {
    $("option").click(function(){
        var filt1 = $(this).attr('id');     
        $('#filter2 option').hide();
        $('#filter2 option.'+ filt1).show();
    });
});

But as charlietfl said, hiding options via CSS isn't cross browser compatible, so you may want to do it the way they said.



来源:https://stackoverflow.com/questions/45045590/how-can-i-add-a-variable-to-a-jquery-selector-of-a-pseudo-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!