1

私はこのjQueryステートメントを持っています:

$(document).ready(function() {
$('#toggle-link').click(function(){
$(this).text($(this).text() == '+' ? '-' : '+');
 $('#box-to-toggle').toggle();

});
});

#box-to-toggle のインスタンスがいくつかあるので、#toogle-link リンクをクリックすると、ボックスのすべてのインスタンスが開閉します。リンクが同じdivのボックスのみを開くように、これを解決する方法を誰かに教えてもらえますか? これがhtml構造です。

<div id='holder'>
    <div id='toggle-link'>+</div>
    <div id='box-to-toggle'>
        <!-- hide / show content here -->
    </div>
</div>
<div id='holder'>
    <div id='toggle-link'>+</div>
    <div id='box-to-toggle'>
        <!-- hide / show content here -->
    </div>
</div>
<div id='holder'>
    <div id='toggle-link'>+</div>
    <div id='box-to-toggle'>
        <!-- hide / show content here -->
    </div>
</div>
<div id='holder'>
    <div id='toggle-link'>+</div>
    <div id='box-to-toggle'>
        <!-- hide / show content here -->
    </div>
</div>

どんな助けでも感謝します

4

4 に答える 4

4

複数の ID は健康に悪いので、それらを classNames に変更します。その後:

$(this).parent().find(".box-to-toggle").toggle();
于 2013-04-12T08:25:23.640 に答える
1

すべての回答が示唆するように、一意のid常に使用し、現在の質問のclass代わりに使用します。id

$('.toggle-link').click(function () {
    $(this).text($(this).text() == '+' ? '-' : '+');
    $(this).next("div.box-to-toggle").toggle();
});
于 2013-04-12T08:40:02.063 に答える
1

マークアップに、1 つのページ内の複数の要素にインスタンス化された ID がいくつかあることを確認してください。とが複数#holder, #toggle-linkあり#box-to-toggleます。

これは、id表記をclassに変更した方がよいため、マークアップは id を class に変更する必要があります。

<div class='holder'>
   <div class='toggle-link'>+</div>
   <div class='box-to-toggle'>
       <!-- hide / show content here -->
   </div>
</div>
.....more divs......

jQueryは1つの変更で問題ありません。代わりに使用できるクラス名でdivを切り替えないでください.next(), .siblings()

.next():

$('.toggle-link').click(function () {
   var $this = $(this);
   $this.text($this.text() == '+' ? '-' : '+');
   $this.next('.box-to-toggle').toggle();
});

.siblings():

$('.toggle-link').click(function () {
   var $this = $(this);
   $this.text($this.text() == '+' ? '-' : '+');
   $this.siblings('.box-to-toggle').toggle();
});

#id表記が.クラス表記に変わります。

于 2013-04-12T08:36:31.617 に答える