admin管理员组

文章数量:1422317

I am doing with this plugin :

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

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

How can I select the closest span of linkType1-anchors for displaying as tooltip ?

Currently I am doing :

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

I am doing with this plugin :

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

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

How can I select the closest span of linkType1-anchors for displaying as tooltip ?

Currently I am doing :

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 
    });
});
Share Improve this question asked Apr 2, 2012 at 8:01 tusartusar 3,4346 gold badges39 silver badges61 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Your span elements aren't ancestors of the links, so closest (which looks for a match for the selector on the current element or its ancestors) isn't what you're looking for.

Based on your markup, you might want next("span") (which will find the next sibling, but only if it's a span; it doesn't continue with subsequent siblings) or possibly nextAll("span").first() (which will find the first next sibling that's a span, in case you ever put something between the a and the span), which finds all subsequent siblings with nextAll and then grabs the first of them (the one nearest the link) via first. So

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

or

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

closest() finds the closest parent element. You are looking for a sibling:

jQuery(this).next("span").html()

$(this) is referring to bodyHandler function. Try this

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

Why not use find() instead? As closest() transverses up the DOM tree

本文标签: javascriptjQueryclosest() gives quotnullquot valueStack Overflow