2012-04-02 60 views
0

我這個plugin做:jQuery.closest()給出了 「零」 的價值

<table> 
<tr> 
    <td> 
    <a class="linkType1" href="google.com"> 
     Google 
    </a> 
    <span style="display: none;">Goooooooooooogle</span> 
    </td> 
</tr> 

<tr> 
    <td> 
    <a class="linkType1" href="yahoo.com"> 
     Yahoo 
    </a> 
    <span style="display: none;">Yaaaaaaaaaaaaaaho</span> 
    </td> 
</tr> 
</table> 

如何選擇的linkType1 -anchors的closestspan顯示爲工具提示?

目前我做的:

jQuery(document).ready(function() { 
    jQuery("a.linkType1").tooltip({ 
     bodyHandler: function() { 
      alert(jQuery(this).closest("span").html()); // this alert is showing `null` 
      return "hi"; // i need to setup the alerted content here 
     }, 
     showURL: false 
    }); 
}); 

回答

4

span元素不聯繫的祖先,所以closest(其中尋找匹配當前元素或其祖先在選擇器)是不是你」重新尋找。

根據您的標記,你可能想next("span")(這將尋找下一個兄弟,但只有當它是一個跨度,它不與隨後的兄弟姐妹繼續)或可能nextAll("span").first()(這將找到的第一個兄弟,這是一個如果你曾經在aspan之間加入了一些東西,後者會找到所有後續的兄弟姐妹,然後通過first獲取其中的第一個(最靠近鏈接的那個)。所以

// If the `span` will always be the very next sibling 
alert(jQuery(this).next("span").html()); 

// If you may put something between the `a` and the `span` at some point 
alert(jQuery(this).nextAll("span").first().html()); 
+0

我覺得太多票了...... 7分鐘後會接受。謝謝T.J,那正是我需要的。 +1 – tusar 2012-04-02 08:10:02

+0

你能否看看我的另一個問題? http://stackoverflow.com/q/8937158/778687 – tusar 2012-04-02 08:10:43

2

closest()查找最接近元素。您正在尋找一個兄弟:

​​
+0

根據API:獲取匹配選擇器的第一個元素,從當前元素開始,並通過DOM樹進行。 – mamoo 2012-04-02 08:08:01

+0

父元素或**當前**元素(如果它匹配選擇器)。 – Tadeck 2012-04-02 08:08:36

+0

+1請你看看我的另一個問題? http://stackoverflow.com/q/8937158/778687 – tusar 2012-04-02 08:11:40

0

$(this)指的是bodyHandler功能。 試試這個

alert(jQuery(linkType1).closest("span").html()); 

爲什麼不使用find()呢?最接近()橫穿DOM

+0

這也可以解決我的想法。 +1 – tusar 2012-04-02 08:08:32

+0

*「'$(this)'指的是bodyHandler函數」*不,它不是。 body處理函數是通過將'this'設置爲DOM元素來調用的(大多數插件與jQuery的工作方式一致)。 – 2012-04-02 08:08:41