有没有办法将 'this' 转移到不同的功能?

Is there a way to transfer 'this' to a different function?

我有一个实例,我需要将 this 的值转移到不同的函数以供使用。显而易见的解决方案是使用全局变量,但我听说这不是好的做法。这是我的代码:

$('.title').each(function(){
   $(this).click(function(){
       titleThis = this;
   });  
});

$('.post-footer').click(function(){
    $(titleThis).css('background','red');
});

JsFiddle

如何在不使用全局变量的情况下做到这一点?

旁注:我不能做这样的事情:

$('.title').each(function(){
       $(this).click(function(){
           var titleThis = this;
           $('.post-footer').click(function(){
               $(titleThis).css('background','red');
           });
       });  
    });

因为我在这个例子中代替 .click() 使用的插件 (JQuery Waypoints) 在我尝试堆叠它时抛出错误(不确定为什么)。当我在第一个示例中使用全局变量时它工作正常,我只是想尽可能避免使用全局变量。

编辑: 由于我的示例代码似乎存在一些问题,某些解决方案在我的真实代码中不起作用,这是我的实际代码块:

    $('.title').each(function() {
            //creating the waypoint
          $(this).waypoint(function(direction) {
//declaring global variable as this
              titleThis = this;
              //if below waypoint, do animation
              if (direction === "down"){
                  //fix the title
                  $(this.element).addClass('titleFixed');
                  //slide right
                  $(this.element).animate({left:'10%'},250,function(){
                      //slide title decoration right
                      $(this).next().animate({left:'0'},50);
                  });
                  //if above waypoint, undo animation
              }else{
                  //unfix the title
                  $(this.element).removeClass('titleFixed');
                  //animate left
                  $(this.element).animate({left:'-3.5%'},240,function(){
                      //animate title direction left
                    $(this).next().animate({left:'-3.5%'},150);
                  });
              }
          });
        });
      $('.post-footer').waypoint(function() {
         $(titleThis.element).css('background','red');
      });

如果我尝试将第二个 .waypoint 函数嵌套在第一个函数中,则会出现错误。

您不需要全局变量。只需将您的代码包装在一个自执行函数中:

(function(){
    var titleThis;
    $('.title').click(function(){
        titleThis = this;
    });
    $('.post-footer').click(function(){
        $(titleThis).css('background','red');
    });
})();
// `titleThis` is not defined here.

必要时使用全局变量没有错。错误的是在将值(或引用)作为函数参数传递时过度使用全局变量更合适。这不是你的情况,因为 $(.post-footer) 上的点击处理程序是独立触发的,并且不与 $(.title)

的点击处理程序共享变量范围

不清楚您试图用您的代码实现什么。但是使用全局变量来标记最后单击哪个 div 是完全可以的。如果这就是你的目标。

我建议先声明和定义全局变量:

var titleThis = null;

您也可以尝试仅使用 css 并添加一个 .selected class 供您定位。

$('.title').each(function(){
   $(this).click(function(){
       $('.title.selected').removeClass('selected'); // Prevents having multiples selected.
       $(this).addClass('selected')
   });  
});

$('.post-footer').click(function(){
    $('.title').css('background', ''); // Undo css on previous titles
    $('.title.selected').css('background','red');
});