简体   繁体   中英

Show / hide divs clarification with javascript

A highly similar question has been asked already, and it has partly solved my problem, but I'd like to know if class or id NAMES can be used in this example instead of ul li - .menu , #menu , etc.

css: div { display:none; background:red; width:200px; height:200px; } div { display:none; background:red; width:200px; height:200px; }

js:

$(function() {
    $('ul li').each(function() {
        $(this).click(function(e) {
            var i = $(this).index();
            $('div').hide();
            $('div:eq('+i+')').show();
        });
    });
});

Here's the jsfiddle for this example: http://jsfiddle.net/Z3Hj7/

Apologies in advance if this question is stupid, but I've been mucking about with it for a while and cant figure it out.

Yes, you can:

$(function() {
    $('#menu .list').click(function(e) {
        var i = $(this).index();
        $('div').hide();
        $('div:eq('+i+')').show();
    });
});

There is no need at all for using a loop.

Here is a demo

To improve your js, you can use the arguments of the $.each function:

$(function() {
    $('ul li').each(function(i, e) {
        $(e).click(function() {
            $('div').hide();
            $('div:eq('+i+')').show();
        });
    });
});

I wrote this snippet some time ago to hide anything with an id. The elements img, div, a, li ul, table etc: all need to have style set to visible/relative visibility: visible; position: relative;

The function changes visible to hidden to hide the element then sets the position to absolute to keep the element from creating a white space in its position.

Fiddled http://jsfiddle.net/ShawnsSpace/URRDy/

<div id="togglethis" style="visibility: visible; position: relative; border: 4px dotted;">Click the button to toggle this Div</div>

<button onclick="toggle('togglethis');">Toggle</button>

    <script type="text/javascript">
//<![CDATA[
function toggle(obj) {
    var item = document.getElementById(obj);
    if (item.style.visibility=='visible') {
        item.style.visibility = 'hidden';    
     }
    else {
        item.style.visibility = 'visible';
     }
     //
    if (item.style.position=='relative') {
    item.style.position = 'absolute'; 
    }
    else { 
    item.style.position = 'relative'; 
    }   
}
//]]>
</script>

要回答有关使用ID和类作为选择器的问题,可以的,您可以: http : //jsfiddle.net/Z3Hj7/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM