用jquery获取标题

grabbing title with jquery

本文关键字:标题 获取 jquery      更新时间:2023-09-26

单击<li>时,我正试图获取它上的"title"。它不断返回undefined。

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 = '';
});
});

这不管用吗?

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

"this"可能不是li。或者浏览器有漏洞(IE?)。你的代码对我来说似乎是正确的。

您应该在单击的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
    });
});
$("li").on('click',function () {alert($(this).attr('title');)});

如何在li元素上附加单击处理程序?您确定处理程序中的this指向li元素吗。

我会尝试记录this并找出它指向什么。

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

我猜应该是:

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