0

なぜこれが機能しないのですか?私はとても混乱しているので、ここに何時間も座っていました... jsFiddle http://jsfiddle.net/5SHdr/8/で完全に動作します

<!DOCTYPE html>
<html>
<head>
<style>
body
{
    padding:0;
    margin:0;
}

#menu
{
    width:100%;
    background-color:#ddd;
}

#menu .link
{
    display:inline-block;
    margin-left:5px;
    margin-right:5px;
    padding:5px;
    cursor:pointer;
}
#menu .link.active
{
    color:blue;
}

#main
{
    padding:5px;
}

#main .content
{
    display:none;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script>
$('.link').click(function () {
    if ($(this).hasClass('active')) return false;
    var name = $(this).attr('id');
    var $visible = $('#main .content:visible');
    $('.active').removeClass('active');
    $(this).addClass('active');
    if ($visible.length == 0) showContent(name);
    else $visible.fadeOut(500, function () {
        showContent(name);
    });
});

function showContent(name) {
    $('#main .' + name).fadeIn(500);
}
</script>
</head>
<body>
<div id="menu">
    <div class="link" id="home">Home</div>
    <div class="link" id="blog">Blog</div>
    <div class="link" id="about">About</div>
</div>
<div id="main">
    <div class="home content">This is the home content.</div>
    <div class="blog content">This is the blog content.</div>
    <div class="about content">This is the about content.</div>
</div>
</body>
</html>

私が見逃している本当に単純なものはありますか?

4

3 に答える 3

0

あなたのフィドルのコードは機能します。ただし、イベントは $(document).ready 関数内に配置する必要があります。または、本文を閉じる前にスクリプトをページの下部に移動することもできます

于 2013-07-24T02:57:31.887 に答える
0

I have updated this as the answer from @Arun-P-Johny above did not work with IE8.

$(document).ready(function ($) {
    $('.link').click(function(e){ 
        if ($(this).hasClass('active')) return false;
        var name = $(this).attr('id');  
        var $visible = $('#main .content:visible');
        $('.active').removeClass('active');
        $(this).addClass('active');
        if ($visible.length == 0) showContent(name);
        else $visible.fadeOut(500, function () {
            showContent(name);
        });
    });
})
于 2013-07-30T13:13:51.920 に答える
0

スクリプトは dom の準備ができていません。左側のパネルの 2 番目のドロップダウンで選択したフィドルではonload、スクリプト パネルのスクリプトがウィンドウの読み込みイベントで実行されることを意味します。

jQuery(function($){
    $('.link').click(function () {
      console.log('x')
        if ($(this).hasClass('active')) return false;
        var name = $(this).attr('id');
        var $visible = $('#main .content:visible');
        $('.active').removeClass('active');
        $(this).addClass('active');
        if ($visible.length == 0) showContent(name);
        else $visible.fadeOut(500, function () {
            showContent(name);
        });
    });
})

デモ:プランカー

于 2013-07-24T02:55:35.290 に答える