【问题标题】:JS this function issuesJS这个函数问题
【发布时间】:2016-03-17 15:41:53
【问题描述】:

最近我遇到了这个问题,请任何人帮助我。我正在尝试通过此功能显示和隐藏一个 div。

HTML:

<div class="question_frame">
    <div class='help'>?</div>
    <div class="help_content">Show & hide this text</div>
</div>

JavaScript:

$(".question_frame").find( '.help' ).click(function(){
    $( this ).find( '.help_content' ).toggle(1000);
});

【问题讨论】:

    标签: javascript html toggle this


    【解决方案1】:

    它是兄弟姐妹而不是孩子,使用.next()

    $(".question_frame").find( '.help' ).click(function(){
        $( this ).next( '.help_content' ).toggle(1000);
    });
    

    该事件在.help 上触发,而不是在.question_frame 上触发。这里this指的是触发事件的元素,即.help

    $(function () {
      $( '.help_content' ).hide();
      $(".question_frame").find( '.help' ).click(function(){
        $( this ).next( '.help_content' ).toggle(1000);
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="question_frame">
      <div class='help'>?</div>
      <div class="help_content">Show & hide this text</div>
    </div>

    参见上面的工作 sn-p。

    如果中间有什么,你可以使用.nextAll()

    $(function () {
      $( '.help_content' ).hide();
      $(".question_frame").find( '.help' ).click(function(){
        $( this ).nextAll( '.help_content' ).first().toggle(1000);
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="question_frame">
      <div class='help'>?</div>
      <div class="some">Some?</div>
      <div class="help_content">Show & hide this text</div>
    </div>

    或者,您也可以使用.siblings()

    $(function () {
      $( '.help_content' ).hide();
      $(".question_frame").find( '.help' ).click(function(){
        $( this ).siblings( '.help_content' ).toggle(1000);
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="question_frame">
      <div class='help'>?</div>
      <div class="some">Some?</div>
      <div class="help_content">Show & hide this text</div>
    </div>

    【讨论】:

    • 非常感谢 :)
    • 先生,有问题。如果我有其他这样的 div 则无法正常工作。
      ?
      大家好。
      2 显示和隐藏此文本
    • @FerozAhmed 尝试使用.nextAll().first(),请不要使用sir
    • 很抱歉再次询问,但请检查一下,它不适用于此部分。
      这个需要点击后显示?
    • @FerozAhmed 有什么问题?你能在你原来的帖子里更新一下吗?
    猜你喜欢
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2014-06-29
    • 2011-02-13
    • 2011-04-24
    • 2011-08-26
    相关资源
    最近更新 更多