2012-03-28 35 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(""); 
});