嵌套的javascript函数失去了“这个”

时间:2013-04-10 04:58:17

标签: javascript jquery

我有一个嵌套的函数,失去了“this”

的适当范围
if(tabNav === true){

$("." + tabNavClass).show();
tabNavItem.first().addClass("active");//active class on first li
tabNavItem.each(function(i){
    $(this).attr("rel",(i + 1));
});                         

tabNavItem.on("click", function(e){

    tabNavClick();
    //this works, but i don't want it defined here. i want it in the tabNavClick() function
    //var data = $(this).attr("rel");
    //console.log(data);
    e.preventDefault();

});             

}           


//tab nav function          
function tabNavClick(){

// REGISTERS UNDEFINED HERE B/C LOSES SCOPE OF "THIS". FIX?!                    
var that = $(this);
var data = that.attr("rel");
console.log(data);

tabNavItem.removeClass("active");//remove existing active class

};

我已经尝试var that = $(this),但这不起作用,我不认为.call会在这种情况下起作用。如何让$(this).attr("rel");返回我想要的rel#值而不是undefined

3 个答案:

答案 0 :(得分:2)

$(this)传递给函数

  tabNavClick($(this));

  function tabNavClick(obj){
     var that = obj;
     ....

另外,您可以将函数tabNavClick作为单击处理程序传递并执行事件

  tabNavItem.on("click",tabNavClick)

  function tabNavClick(e){
      e.preventDefault();
      var that=$(this);
   }

答案 1 :(得分:2)

如果您希望tabNavClick()拥有所需的this值,则需要在调用时指定:

tabNavItem.on("click", function(e){

    tabNavClick.call(this);
    //this works, but i don't want it defined here. i want it in the tabNavClick() function
    //var data = $(this).attr("rel");
    //console.log(data);
    e.preventDefault();

});     

调用函数的方式决定this值。如果它不是方法调用且您没有使用.call().apply(),则this将在任何函数调用时重置。在这种情况下,您可以使用tabNavClick.call(this)使this值成为您想要的值。


当然,您可以更改tabNavClick以获取要操作的对象的参数:

tabNavItem.on("click", function(e){

    tabNavClick(this);
    //this works, but i don't want it defined here. i want it in the tabNavClick() function
    e.preventDefault();

});     

//tab nav function          
function tabNavClick(obj){

    var data = $(obj).attr("rel");
    console.log(data);
}

答案 2 :(得分:0)

您可以将tabNavClick本身作为点击处理程序传递:

tabNavItem.on("click", tabNavClick);

这会以tabNavClick指向点击的项目的方式调用this

您可以让tabNavClick返回false以防止事件冒泡。此外,您还可以tabNavClick接受该事件:

function tabNavClick(e) {
    // ...
    e.preventDefault();
}