1

divをクリックして、彼の子供を表示させたいと思います。問題は、私がそれらのdivの長いリストを持っていることです。各divには子があります。以下では、divの「エチケット」をクリックして、子のdivの「詳細」を表示または非表示にします。

<div class="etiquette">
  <span class="date">13-07</span>
  <span class="titre">LOREM IPSUM 1</span>
     <div class="detail"><p>lorem ipsum 1</p></div>
</div>
<div class="etiquette">
  <span class="date">14-07</span>
  <span class="titre">LOREM IPSUM 2</span>
     <div class="detail"><p>lorem ipsum 2</p></div>
</div>
<div class="etiquette">
  <span class="date">14-07</span>
  <span class="titre">LOREM IPSUM 3</span>
     <div class="detail"><p>lorem ipsum 3</p></div>
</div>

使用したいスクリプトは次のとおりです。

$(document).ready(function() {
    $(".etiquette").children(".detail").css("display", "none");
    $(this).toggle(function() {
        alert("clicked");
        $(this).children("div.detail").css("display", "block");
    }, function() {
        alert("clicked again");
        $(this).children("div.detail").css("display", "none");
    });
});

以下はうまく機能します:

$(this).toggle(function() {
    alert("clicked");
});

以下もうまくいきます。ただし、クリックしたdivの子だけでなく、すべてのdivの「詳細」を表示または非表示にします。

$(this).toggle(function() {
    alert("clicked");
    $(".etiquette").children("div.detail").css("display", "block");
}, function() {
    alert("clicked again");
    $(".etiquette").children("div.detail").css("display", "none");
});
});

私は何を間違っているのですか?よろしくお願いします。

4

4 に答える 4

1

あなたの$(this)は、私が推測するドキュメント自体を指しています。

これを試して、

$(document).ready(function() {
  $(".etiquette").children(".detail").css("display", "none");
  $(".etiquette").click(function(){
    $(this).children("div.detail").toggle();
  });
});

私はコードをテストしませんでした。それがうまくいくことを願っています。

于 2012-07-16T17:11:28.733 に答える
0
$(".etiquette").children(".detail").css("display", "none");
$('.etiquette').click(function() {
    $(this).find('.detail').toggle();
});​

jsFiddle の例

あなたのコードの何が問題なのかについては、あまりにも多くのことがわかります。最初の行は、クラスを持つdetail要素の子であるクラスを持つすべての要素を非表示にしetiquetteます (あなたが持っていて、私は変更しませんでした)。コードの次のブロックは、クリック イベントをクラスの要素にバインドし、クラスetiquetteの子要素の表示を切り替えますdetail

于 2012-07-16T17:13:37.957 に答える
0

これを変える:

$(this).toggle(function() {

に:

$('.etiquette').toggle(function() {

これthisは、要素でdocumentはなくオブジェクトを参照します。.etiquette

注: jQuery 1.7 の時点で、トグル マウス イベントを使用することは推奨されていません。

http://jsfiddle.net/f9BcB/

于 2012-07-16T17:14:24.410 に答える
0

.each 関数を使用して各 div にトグル関数をバインドしようとしましたか?

元:

$('.etiquette').each(function(){
  $(this).click(function(){
    //Enter toggle function here
  });
});
于 2012-07-16T17:16:53.207 に答える