Nested jQuery toggle statements

2019-09-09 04:12发布

问题:

I have a situation where I have "nested" toggle statements in jQuery.

I have a bunch of selects that allow a user to set a day as open or closed.

I then have a select that allows a user to show details about all the days. Details are hidden by default (this is causing my problem).

If a user sets a day to closed I don't want to display that day when the user selects to display details for all days. Eg. if monday is set to closed and the rest of the week is open and the user selects "display details" it would show the details for all days except Monday.

This works fine if I start with all the details showing (you can hide and show the details and closed days are not displayed). But by default the details are hidden and if a user sets some days to closed and then displays the details it displays the details for all days, even the closed ones.

Is there an easy way to persist the "nested" toggle when the toggle for the containing div is changed?

I have put together a crude example of the sort of situation in this jFiddle.

http://jsfiddle.net/yTt3t/16/

Thanks for any assistance.

回答1:

Indeed, the problem is that the parent element of the elements you change the visibility of is initially hidden. I assume that jQuery performs some optimization to avoid unnecessary CSS and DOM changes.

It works though if you pass a boolean to .toggle() [docs], which, IMO, is better anyway, it ensures that the state of the element is always correct:

$("#monday_select").change(function(){
    $("#monday_details").toggle(this.value === 'Open');
});

$("#tuesday_select").change(function(){
    $("#tuesday_details").toggle(this.value === 'Open');
});

The argument controls whether the element should be shown (true) or hidden (false).

DEMO