我有一个嵌套函数,它失去了“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
?
最佳答案
将 $(this)
传递给函数
tabNavClick($(this));
function tabNavClick(obj){
var that = obj;
....
此外,您可以将函数 tabNavClick 作为点击处理程序传递并获取事件
tabNavItem.on("click",tabNavClick)
function tabNavClick(e){
e.preventDefault();
var that=$(this);
}
关于javascript - 嵌套的javascript函数丢失 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15917262/