如何获得$(this)选择器的特定子项(两个孩子中的一个)?

时间:2018-01-28 00:56:34

标签: javascript jquery jquery-selectors this

我已经尝试过以下各项解决方案:How to get the children of the $(this) selector?

我有两个按钮,一个用于星期五,一个用于星期六。我想只在我点击的按钮上显示微调器图标,而不是两个按钮。

下面的两次代码尝试不会产生任何错误。他们根本不工作。



(function($) {

  $(document).ready(function(){

    $(this).on('click', function(){
      $(this).children('.hide').toggleClass('.hide');
    });

  });

})( jQuery );

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" rel="stylesheet"/>

<a href="#" class="waves-effect waves-light btn mb15 w100">
  <span class="button-text">Friday </span>
  <i class="fa fa-life-ring fa-spin hide"></i>
</a>
<a href="#" class="waves-effect waves-light btn mb15 w100">
  <span class="button-text">Saturday</span>
  <i class="fa fa-life-ring fa-spin hide"></i>
</a>
&#13;
&#13;
&#13;

&#13;
&#13;
(function($) {

  $(document).ready(function(){

    $(this).on('click', function(){
      $('.hide', this).toggleClass('.hide');
    });

  });

})( jQuery );
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" rel="stylesheet"/>

<a href="#" class="waves-effect waves-light btn mb15 w100">
  <span class="button-text">Friday </span>
  <i class="fa fa-life-ring fa-spin hide"></i>
</a>
<a href="#" class="waves-effect waves-light btn mb15 w100">
  <span class="button-text">Saturday</span>
  <i class="fa fa-life-ring fa-spin hide"></i>
</a>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

点击按钮查找微调器类并删除hide类:

$('.waves-effect').click(function(){
   $(this).find('.fa-spin').removeClass('hide');
});

答案 1 :(得分:2)

this是基于上下文的,您需要了解何时使用它。

如果您不确定this的背景,可以随时使用console.log(this)

这是对您的代码的修复:

&#13;
&#13;
(function($) {

  $(document).ready(function(){

    $('a.btn').on('click', function(){
      $(this).find('i').toggleClass('hide');
    });

  });

})( jQuery );
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" rel="stylesheet"/>

<a href="#" class="waves-effect waves-light btn mb15 w100">
  <span class="button-text">Friday </span>
  <i class="fa fa-life-ring fa-spin hide"></i>
</a>
<a href="#" class="waves-effect waves-light btn mb15 w100">
  <span class="button-text">Saturday</span>
  <i class="fa fa-life-ring fa-spin hide"></i>
</a>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

将点击事件应用于按钮而不是文档。