问题
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