Show a div when click on related link and hide the

2019-02-19 09:15发布

I've this code:

<head>
<script>

        $(document).ready(function(){
        // Optional code to hide all divs
        $("div").hide();
          // Show chosen div, and hide all others
        $("a").click(function () 
        {
            $("#" + $(this).attr("class")).show().siblings('div').hide();
        });

    });

</script>

</head>

<body>
    Click a button to make it visible:<br /><br />
<a href="" class="one">One</a>
<a href="" class="two">Two</a>
<a href="" class="three">Three</a>
<a href="" class="four">Four</a><br /><br />

    <div id="one">One</div>
    <div id="two">Two</div>
    <div id="three">Three</div>
    <div id="four">Four</div><br/><br/>




</body>

I want to display a div when the related link is clicked. The problem is that this process lasts only few seconds. Someone knows why? Thanks

3条回答
【Aperson】
2楼-- · 2019-02-19 09:21

Use preventDefault()

        $("a").click(function (e) 
    {
            e.preventDefault();
        $("#" + $(this).attr("class")).show().siblings('div').hide();
    });

Demo Fiddle

查看更多
We Are One
3楼-- · 2019-02-19 09:33

You should specify # in the href:

<a href="#"></a>

Here is the demo: JSFiddle

查看更多
We Are One
4楼-- · 2019-02-19 09:44

You can add common class to all divs like

<div id="one" class="div">One</div>
<div id="two" class="div">Two</div>
<div id="three" class="div">Three</div>
<div id="four" class="div">Four</div>

js:

$("a").click(function (){         
    $(".div").hide();            
    $("#" + $(this).attr("class")).show().siblings('div').hide();
});
查看更多
登录 后发表回答