我正在使用这个plugin:
<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>
如何选择closest
span
of linkType1
-anchors以显示为工具提示?
目前我正在做的是:
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
});
});
发布于 2012-04-02 16:05:17
您的span
元素不是链接的祖先,所以closest
(在当前元素或其祖先上查找选择器的匹配项)不是您要寻找的。
根据您的标记,您可能需要next("span")
(它会找到下一个同级,但前提是它是一个跨度;它不会继续后续的同级)或nextAll("span").first()
(它会找到下一个跨度的同级,以防您在a
和span
之间放了什么东西),它会查找所有后续的具有nextAll
的同级,然后通过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());
发布于 2012-04-02 16:03:47
closest()
查找最接近的父元素。您正在寻找同级:
jQuery(this).next("span").html()
发布于 2012-04-02 16:06:42
$(this)
指的是bodyHandler函数。尝尝这个
alert(jQuery(linkType1).closest("span").html());
为什么不使用find()
呢?因为DOM
()在DOM
树中向上遍历
https://stackoverflow.com/questions/9972775
复制相似问题