2009-08-12 84 views
0

我有一個無序列表如下:使用jQuery添加列表標題

<div class="blueBoxMid"> 
    <ul> 
    <li>First item <em>This is the hover text</em></li> 
    <li>Second item <em>This is the hover text</em></li> 
    </ul> 
</div> 

我想使用jQuery來產生這樣的:

<div class="blueBoxMid"> 
    <ul> 
    <li title="This is the hover text">First item</li> 
    <li title="This is the hover text">Second item</li> 
    </ul> 
</div> 

我當前的代碼看起來liket他的,但我不能不能讓它工作。幫助任何人? :)

$('.blueBoxMid li').each(function(){ 
    $('.blueBoxMid li em').hide(); 
    $('.blueBoxMid li').attr('title', $(this).children('em').text()).hover(function(){$(this).css('cursor', 'help')}); 
}); 
+0

其在這裏工作...與jquery 1.3.2 你面臨的問題是什麼? – 2009-08-12 08:30:36

回答

4

嘗試是這樣的:

$('div.blueBoxMid ul li').each(function() { 
    var tooltip = $(this).children('em').remove().text(); 
    $(this).attr('title', tooltip).css('cursor', 'help'); 
}); 

基本上,它遍歷每一<li>元素,刪除其<em>元素並得到<em>元素的文本內容,然後將其應用title屬性和CSS風格。 CSS樣式可以始終(不僅在懸停上),因爲它只會在反正盤旋時改變光標。

+0

我自己想通了,但代碼看起來與此相同,儘管我使用$(this).children('em')。hide()而不是remove()。 – 2009-08-12 08:32:34

+0

好的。 'remove()'可以被認爲更有效率,因爲元素從DOM中被移除,而不是被CSS樣式化。此外,如果您仍在使用'hover()',請刪除它,因爲它可能會在第一次元素被徘徊時導致一些差異,並且之後所有的徘徊只會進行不必要的調用,而對CSS不起作用(因爲它已經設置在第一次通話後給「幫助」。) – Blixt 2009-08-12 08:43:20

+0

謝謝,用remove():)關掉hide() – 2009-08-12 10:52:30

1

jQuery有時很難獲得隱藏元素的屬性,所以嘗試在隱藏em元素之前設置li元素的標題。

請注意,您的each()函數中的$('.blueBoxMid li em')$('.blueBoxMid li')仍然指代符合這些條件的所有元素;用$(this)依次引用每一個。如果你想隱藏所有的'.blueBoxMid li em'元素,你的線路$('.blueBoxMid li em').hide();不需要在每個循環內。