I got this HTML structure:
<form>
<input class="myTrigger" type="radio" value="1"/>
<开发者_如何学Go;input class="myTrigger" type="radio" value="2"/>
<fieldset>
<ul class="class1">
<li></li>
</ul>
<ul class="class2">
<li></li>
</ul>
</fieldset>
<fieldset>
<ul class="class2">
<li></li>
</ul>
<ul class="class2">
<li></li>
</ul>
</fieldset>
</form>
With jQuery, I need to go through each ul
and hide the ones that don't have class myClass
(wich is defined by the checked
radio
.myTrigger
) then i need to check for the now empty fieldset
's (ie: fieldsets
where no ul has class myClass
) and hide them entirely.
So far, i was able to hide the desired ul
's, but not the fieldsets
. This is what i got:
function myFunction() {
var myClass = "class"+($("radio:checked").attr("value"));
var productGroup = $("form ul");
$("form fieldset").each(function(index){
groupCheck = 0;
$.each(productGroup, function(index, obj){
if($(obj).hasClass(myClass))
{
groupCheck += 1;
$(obj).show();
}
else
{
$(obj).hide();
};
})
if (groupCheck == 0)
{
$(this).hide();
}
else {
$(this).show();
};
});
};
myFunction();
$(".myTrigger").change(myFunction);
Also i got other scripts on the same page toggling the same ul's
ex:
(legend).click(function(){$(this).siblings("ul").toggle();});
so can't hide the fieldsets based on the ul
's beeing hidden already. instead I need to look for the classes ("myClass") beeing present or not.
(ie: while the small script toogles the ul's just for user convinience "myFunction" needs to filter the ul's and fieldsets to be shown based on "myTrigger" selection.)
No need for loops; just target the things you want to show/hide with appropriate selectors:
var myClass = 'class' + $('radio:checked:first').attr('value');
// Hide all the <ul>s
$('ul.' + myClass).hide();
// First, show all the fieldsets, in case any were hidden earlier
$('fieldset').show();
// Now hide the ones that don't have any visible <ul>s inside
$('fieldset:not(:has(ul:visible))').hide();
精彩评论