如何隐藏元素并在点击时显示新元素?

时间:2012-09-18 18:15:57

标签: javascript jquery html css fadein

我有三张图片,点击后会显示一个包含文字的隐藏元素。但是,我想确保在显示其他2个隐藏元素时隐藏它们。所以,如果我点击#img2,那么将显示#text2但是#text1和#text3将被隐藏。此外,这可能只是一个语法错误,但当我试图将我的所有代码放在脚本标记下时,它将无法正常工作。我也喜欢将所有jquery放在脚本标记中,而不是使用HTML中的onclick功能。我对jquery很新,所以所有的帮助都表示赞赏。提前谢谢!

<div id = "img1" onclick = "$('#text1').fadeIn(500)"></div>
<div id = "img2" onclick = "$('#text2').fadeIn(500)"></div>
<div id = "img3" onclick = "$('#text3').fadeIn(500)"></div>

<div id = "text1" hidden></div>
<div id = "text2" hidden></div>
<div id = "text3" hidden></div>

<script>
    /* TODO: Put all on-click code here */
</script>

4 个答案:

答案 0 :(得分:1)

保持代码不引人注目是一种很好的做法

HTML

<div id = "img1" class="img">One</div>
<div id = "img2" class="img">Two</div>
<div id = "img3" class="img">Three</div>

<div id = "text1" class="hidden">One</div>
<div id = "text2" class="hidden">Two</div>
<div id = "text3" class="hidden">Three</div>​

CSS

.hidden{display:none}​

的jQuery

$(function(){
    $("div.img").on("click", function(){
       var id = $(this).attr("id").substr(-1);
       $(".hidden").hide();
       $("#text"+id).show();        
    });   
})​

<强> DEMO

答案 1 :(得分:0)

<div id = "img1" onclick = "$('.effect').hide();$('#text1').show()"></div>
<div id = "img2" onclick = "$('.effect').hide();$('#text2').show()"></div>
<div id = "img3" onclick = "$('.effect').hide();$('#text3').show()"></div>

<div id = "text1" class="effect" hidden></div>
<div id = "text2" class="effect" hidden></div>
<div id = "text3" class="effect" hidden></div>

答案 2 :(得分:0)

您可以尝试这样的事情:

<强> HTML:

<div id="div1">One</div>
<div id="div2">Two</div>
<div id="div3">Three</div>

<div id="texts">
    <div id="txt1">Text One</div>
    <div id="txt2">Text Two</div>
    <div id="txt3">Text Three</div>
</div>

<强> JavaScript的:

$(function(){

    // hide every text div (all texts children)
    $( "#texts" ).children().hide();

    // this function hides every text child and than
    // fades in the desired one
    function hideAndShow( toShowSel ) {
        $( "#texts" ).children().hide();
        $( toShowSel ).fadeIn();
    }

    // registering the click event for the divs...
    $( "#div1" ).click( function(){
        hideAndShow( "#txt1"  );
    });

    $( "#div2" ).click( function(){
        hideAndShow( "#txt2"  );
    });

    $( "#div3" ).click( function(){
        hideAndShow( "#txt3"  );
    });
});

可在此处找到实时示例:http://jsfiddle.net/davidbuzatto/FztUN/

答案 3 :(得分:0)

http://jsfiddle.net/uptVT/

<div id = "img1" onclick = "$('.text').hide();$('#text1').show();">img1</div>
<div id = "img2" onclick = "$('.text').hide();$('#text2').show();">img2</div>
<div id = "img3" onclick = "$('.text').hide();$('#text3').show();">img3</div>

<div id="text1" class = "text" hidden>text1</div>
<div id="text2" class = "text" hidden>text2</div>
<div id="text3" class = "text" hidden>text3</div>

<script>
    /* TODO: Put all on-click code here */
</script>​