Elegant way to return element to display:none?

时间:2017-04-06 16:53:05

标签: javascript jquery html css display

I have a dropdown, and a list of elements that default to display:none with css. Currently, when an element is selected from the dropdown it's changed to display:block

What I'm missing, is how to change the element back to display:none once a new one is selected. I know I could write a loop to constantly check every element and change it to display:none but that seems cumbersome. My real problem has about 100 elements, and it seems wasteful to re-hide all of them when 99 of them will already be hidden.

Curious what the most elegant way to do this in jQuery (or javascript) is. A fiddle of what I have is here:

https://jsfiddle.net/3w66k51z/4/

Thanks!

3 个答案:

答案 0 :(得分:5)

I've added $(".sReport").hide(); before your .show() call in order to hide all of the elements.

jQuery.hide() will set the element's display to none

jsfiddle

答案 1 :(得分:1)

You could add state so that you know the currently shown item (if any) and hide just that one element. I understand you don't want to hide all items when most of them will already be hidden.

Here is a simple implementation of this idea.

(I imagine your real problem involves many more hidden items than the fiddle. If not — maybe even if so — this may be a premature optimization, and there’s nothing wrong with calling .hide() or whatever on all items.)

答案 2 :(得分:0)

Create array of your element then create a function to hide all elements but not the one you want to be display.