本文介绍了如何将变量添加到伪类的jquery选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将变量添加到伪元素的jquery字符串选择器中?我已经尝试过以下两个代码,但都没有找到有效的方法,您能帮我吗?

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

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

推荐答案

<option>跨浏览器不支持事件和隐藏!根据首次选择中的值删除并追加

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

首先将#c2中的<option>存储并删除.

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

更改为使用filter1中选项上的值,并使用<select>的change事件.

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

然后在进行更改时...克隆并过滤存储的<option>并将过滤的内容仅放入#filter2

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>

这篇关于如何将变量添加到伪类的jquery选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 06:15