【问题标题】:Target a single instance of multiple classes with Jquery使用 Jquery 定位多个类的单个实例
【发布时间】:2013-04-29 16:44:06
【问题描述】:

我正在设计一个字幕模块,在点击时显示/隐藏字幕。我想在动画完成后更改触发切换按钮的文本。

当存在一个按钮实例时,以下内容有效,但如果存在更多,则文本不会更改。 我对在 DOM 中的移动没有​​扎实的掌握,如何使用 $(this) 来定位活动按钮?

编辑:对于像我这样的其他初学者,请注意这是 JS 范围问题,而不是 DOM 问题。

JS:

$('.btn').click(function(){
    $(this).siblings('.caption').animate({ 
      height: 'toggle'
      }, 200, function() {
       // After animation is done:
       if($('.btn').text() == 'Hide'){
         $('.btn').text('Show');
       } else {
         $('.btn').text('Hide');
       }
    }); 
});

HTML:

<div class="container">  
    <ul class="slides">  
        <li>...</li>
    </ul>
    <div class="caption">
        <p class="txt"><span class="details">...</span></p> 
    </div>
    <div class="btn">
        <p class="txt">Hide</p>
    </div>
</div>

希望能快速解释一下我做错了什么。谢谢!

【问题讨论】:

    标签: jquery dom jquery-selectors


    【解决方案1】:

    尝试保存对外部函数的引用$(this):

     $('.btn').click(function(){ 
    
    var self = $( this );
    
    self.siblings('.caption').animate({ 
    
      height: 'toggle'
    
      }, 200, function() {
    
       // After animation is done:
    
       if(self.text() == 'Hide'){
    
         self.text('Show');
    
       } else {
    
         self.text('Hide');
       }
    }); 
    

    });

    【讨论】:

      【解决方案2】:

      我认为下面标记的行应该有 $(this) 而不是 $('.btn'):

      $('.btn').click(function(){
          $(this).siblings('.caption').animate({ 
            height: 'toggle'
            }, 200, function() {
             // After animation is done:
             if($(this).text() == 'Hide'){ //<-- changed this line
               $(this).text('Show');       //<-- changed this line
             } else {
               $(this).text('Hide');       //<-- changed this line
             }
          }); 
      });
      

      您现在的方式是选择所有 .btn 项目,并且由于有多个项目,它不知道要更改哪一个。

      【讨论】:

        【解决方案3】:

        animate 函数内部的函数丢失了点击的.btn 的引用为this。

        要记住哪个按钮是单击,只需在单击目标之前的var 中保存.animate()

        var btn = $(this)
        

        然后您可以使用btn 访问完整功能中的按钮。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-08-26
          • 2020-08-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多