jQuery,更改切换点击元素的文本正在更改下一个div

时间:2015-07-02 04:47:53

标签: javascript jquery

我有一系列要展示的文章,但是想让用户隐藏/显示,这样他们就不必滚动太多......

我有什么 HTML

<div class="article-header" >Article 1 - Thursday Sept 13, 8:30pm <span class="toggleMe" >( hide )</span></div>
<div class="myContent" >...the content...</div>

<div class="article-header" >Article 2 - Thursday Sept 15, 6:30pm <span class="toggleMe" >( hide )</span></div>
<div class="myContent" >...the content...</div>

ETC.

的Javascript

$( document ).on( 'click', '.toggleMe' , function( event ) {

    event.preventDefault();
    $( this ).closest( 'div' ).next( '.myContent' ).slideToggle( function() {

        if ( $( this ).html() === '( hide )' ) {

            $( this ).html( '( show )' );

        } else {

            $( this ).html( '( hide )' );

        }

    });

});

如果我在切换功能中发出警报,看到“$(this).html()”,我得到“(隐藏)”,所以我假设改变$(这个)的html会改变“(隐藏)“to”(show)“,但它正在将文章DIV的内容改为”(显示)“。

示例:

$( this ).closest( 'div' ).next( '.myContent' ).slideToggle( function() {

    alert ( $( this ).html() );

});

THX。

3 个答案:

答案 0 :(得分:4)

我明白了问题在于你是在排队,这意味着最后一个元素是(&#39; .myContent&#39;)和函数 $(this)< / strong>表示 $(&#39; .myContent&#39;)

如果要更改范围文本,则必须将span分配给变量,对该变量执行html(),这里是代码...

$( document ).on( 'click', '.toggleMe' , function( event ) {
    var spanBtn = $(this);
    event.preventDefault();
    $( this ).closest( 'div' ).next( '.myContent' ).slideToggle( function() {
        if ( spanBtn.html() === '( hide )' ) {
            spanBtn.html( '( show )' );
        } else {
            spanBtn.html( '( hide )' );
        }
    });
});

我还附上了源代码 FIDDLE DEMO

答案 1 :(得分:2)

slideToggle回调this内部引用myContent元素

&#13;
&#13;
$(document).on('click', '.toggleMe', function(event) {
  event.preventDefault();
  var $toggler = $(this);
  $(this).closest('div').next('.myContent').stop().slideToggle(function() {
    //here this refers to the `myContent` element not the clicked `toggleMe`
    //you can also simplify it to
    $toggler.html(function(i, html) {
      return html === '( hide )' ? '( show )' : '( hide )';
    });
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="article-header" >Article 1 - Thursday Sept 13, 8:30pm <span class="toggleMe" >( hide )</span></div>
<div class="myContent" >...the content...</div>

<div class="article-header" >Article 2 - Thursday Sept 15, 6:30pm <span class="toggleMe" >( hide )</span></div>
<div class="myContent" >...the content...</div>
&#13;
&#13;
&#13;

答案 2 :(得分:2)

您正在混合范围 - 此代码正在运行:

$( document ).on( 'click', '.toggleMe' , function( event ) {
    var self = $(this);
    event.preventDefault();
    $( this ).closest( 'div' ).next( '.myContent' ).slideToggle( function() {

        if ( self.html() === '( hide )' ) {
            self.html( '( show )' );
        } else {
            $( this ).html( '( hide )' );
        }
    });
});

Fiddle here