开发者

Jquery Selector, Do NOT include an anchor inside a p tag?

I got one of these:

$('a.retweet').click(function () {
    var retweetText = $(this).closest('.article-content').children('p').text();
}

With a bunch of these:

<p><a开发者_开发技巧 href="">Name</a> stuff written here </p>

But I just want the text inside the p tag and NOT the a href. So how do I just get the text in the p tag?


If the text will always be the last child in the element, use .lastChild.nodeValue.


If you can change the markup, so that the text you want is in a <span>:

<p><a href="">Name</a> <span>stuff written here</span> </p>

the problem is trivial to solve:

$(this).closest('.article-content').children('p').children(':not(a)').text();


You're missing ); in that function. Try this --

jQuery

$('a.retweet').click(function(e) {
    e.preventDefault();
    var retweetText = $(this).closest('.article-content').children('p').text();
    alert( retweetText );     
});

HTML

<div class="article-content">
    <a href="#" class="retweet">Testing</a>
    <p>This is a paragraph</p>
</div>

Working demo: http://jsfiddle.net/G8MfP/


$('a.retweet').click(function() 
{
    var retweetText = $(this).closest('.article-content').children('a').text();
}


You could do this:

$('p').contents().last().text();

So you'd have:

$(this).closest('.article-content').children('p').contents().last().text();

Hope this helps. Cheers


This will return the textNode

$(this)
  .closest('.article-content')
  .children('p')
  .contents()
  .filter(function() { 
    return this.nodeType == 3;
})

This should return the text of that node.

$('a.retweet').click(function () {
    var retweetText = $(this)
                        .closest('.article-content')
                        .children('p')
                        .contents()
                        .filter(function() { 
                          return this.nodeType == 3;
                        }).text();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜