javascript - JS这个函数有问题

标签 javascript html toggle this

最近我遇到了这个问题,请任何人帮助我。我正在尝试通过此函数显示和隐藏一个 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);
});

最佳答案

它是 sibling ,而不是 child ,请使用.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>

请参阅上面的工作片段。

如果中间有东西,您可以使用.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>

关于javascript - JS这个函数有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36065299/

相关文章:

javascript - 仅适用于平板电脑/手机的 JS 脚本

javascript - Bootstrap 切换 : Setting the toggle state of multiple checkbox to 'Off'

javascript - AngularJS 绑定(bind)函数到多个元素

javascript - beforeSave 导致查询不返回任何内容

javascript - 检查周围的表格单元格

javascript - 如何在不影响其他元素的情况下使用bootstrap collapse?

javascript - 检查 Cookie ; load() 如果cookie匹配,需要重新加载才能看到新内容

javascript - 将 resolve() 和 then() 方法与 Promise 混淆

javascript - 如何从 Typescript 模块导出 2 个项目

react-native - 在 React Native 中使用 Flatlist 进行分页(下一个/上一个)