2

.click 内に jQuery 関数がありますが、機能しません。私はjQueryをテストしましたが、動作していますが、.click内のテストとして複数の組み合わせを試しましたが、何らかの理由で正しく動作しません. コンソールは空白で、エラーはないと表示されます。ただし、定義済みの変数が見つからないと言っています...

html:

<body>
    <section id="container_header">
        <header>
            <nav>
                <a id="home">Home</a>
                <a id="about">About</a>
                <a id="work">Work</a>
                <a id="contact">Contact</a>
            </nav>
        </header>
    </section>
    <section id="container_content">
        <div class="section" id="section-home"></div>
        <div class="section" id="section-about"></div>
        <div class="section" id="section-work"></div>
        <div class="section" id="section-contact"></div>
    </section>

CSS を使用して、空の div をレンダリングしていますが、正しく表示されます。jsの場合:

        $(function(){
            $(this).click(function(){
                var pid = $(this).attr("id"); //console says this var is not defined???
                $(this).hide(); //even this does not work???
                //$("div[id^=section-]").hide(); //this works just fine???
                //$(this).closest("#container_header").hide(); //not working???
                //$(this).closest("body").find("#section-" + pid).show(); //no likey???
                //alert("h"); //works
            });
        });

上記のコメントは、機能するものと機能しないものについて説明しています。それはおそらく愚かなことですが、私には見えません。はい、テスト中に、コメントを試す前にコメントを削除しています。

4

3 に答える 3

2

readyハンドラー内でthis、ドキュメント自体にバインドされます。あなたが書いたので:

$(function() {
    $(this).click(function() {  // Here, 'this' is 'document'.
        var pid = $(this).attr("id");
        $(this).hide();
    }
});

id存在しないドキュメントの属性を取得しようとしていますが、ドキュメント自体を非表示にしようとしていますが、これは実現できません。

代わりに、クラス<div>を公開する要素を一致させてみてください。section

$(function() {
    $("div.section").click(function() {
        var pid = $(this).attr("id");
        $(this).hide();
    }
});
于 2012-12-16T09:02:18.517 に答える
1

多分これはあなたが望むものです.あなたの最初のthisものは間違った使い方をしています.タグセレクターでなければなりません.

$(function() {
  $('#container_header a').click(function() {
    $('#container_content > div').hide();
    $('#section-'+this.id).show();
  });
});
于 2012-12-16T09:01:01.643 に答える