2012-03-28 60 views
0

我试着抢在<li>“标题”被点击时它。它保持返回undefined。抓住标题使用jQuery

HTML

<div id="sidebar"> 
     <div class="navigation"> 
    <ul> 

    <li title="../../000_Movies/_assets/playlist.html">فیلم ها</li> 

    </ul> 
</div> 
</div> 

JS

$('.navigation li').click(function() { 
$('.slider').animate({ 
    marginLeft: 0 
}, 500,function() { 
var test = $(this).attr('title'); 
alert(test); 
    location.href = ''; 
}); 
}); 
+2

尝试'.prop(“title”)'in代替'.attr(“title”)''但我认为它应该可以正常工作...... – Pointy 2012-03-28 14:58:13

+0

你确定“this”实际上是“li”元素吗?也许尝试控制台日志记录? – 2012-03-28 14:59:00

+0

你能告诉我们'$(this)'的上下文吗? – 2012-03-28 14:59:18

回答

2

这不起作用?

$('li').click(function(){ 
    alert($(this).attr('title')); 
}); 
1

“这” 也许是不立。或者浏览器有错误(IE?)。你的代码对我来说似乎是正确的

+0

它在FF和铬做这个 – Blainer 2012-03-28 14:59:44

0
$("li").on('click',function() {alert($(this).attr('title');)}); 
0

你是如何连接的单击处理li元素?你肯定this内部处理程序poiting到li元素。

我会尝试登录this并找出它指向。

如果this指向li那么$(this).attr('title')应该工作得很好。

1

您应该创建点击li元件上的关闭。你得到this单击处理程序功能的另一功能里面,这样的this定义会比原有的功能不同。

$('.navigation li').click(function() { 
    // cache the element here 
    var that = $(this); 

    $('.slider').animate({ 
     marginLeft: 0 
    }, 500, function() { 

     // then access that instead here 
     // (we're creating a closure on the that variable) 
     var test = that.attr('title'); 
     alert(test); 
     location.href = ''; 
    }); 
}); 

如果你有两个嵌套函数,其this变量会有所不同:

function foo() { 
    // this here ... 
    function bar() { 
     // ... is different from this here 
    } 
} 

所以建立对...

$('li').click(function() { 
    // $(this) here ... 
    $('something').slider({},100, function() { 
     // ... is different from $(this) here 

    }); 
}); 
0

我猜这将是:

$("li.clickMe").click(function() { 
    $("this").attr("title").whateverYouNeedToDo(""); 
});