在jquery中,我如何检测一个段落是否包含一个链接和一个链接,没有别的

时间:2012-01-26 16:28:53

标签: javascript jquery

我想将一个类'solo'应用于段落中的链接,其中该链接是段落中的唯一元素。

所以这会得到'solo'类:

<p><a>I am alone</a></p>

但这不会:

<p><a>I am not alone</a> because there is more text!</p>

4 个答案:

答案 0 :(得分:7)

你可以这样做:

$('p').filter(function() {
    var $childNodes = $(this).contents();

    return $childNodes
             .not($childNodes.filter('a').first())
             .not(function() {
                 return this.nodeType === 3 && $.trim(this.nodeValue) === '';
             }).length === 0;
});

这将获取所有子节点(包括文本节点)并删除它找到的第一个a元素以及仅包含该集合中的空格的所有文本节点。如果结果集为空,则链接是唯一的子项(单独)。

参考filternotcontentsNode.nodeTypetrim

更新:也许这可以更轻松地完成,但我希望它也适用于HTML包含换行符的情况,这会导致文本节点只包含空格:

<p>
    <a>I am alone</a>
</p>

<p>
    <a>I am not alone</a> because there is more text!
</p>

DEMO

答案 1 :(得分:1)

试试这个

$('p').filter(function(){
    var $childrens = $(this).children();
    return ($childrens.length == 1 
            && $childrens.is('a') 
            && $(this).text() == $childrens.text());
}).addClass('solo');

<强> Demo

答案 2 :(得分:1)

还有一种方法可以做到这一点:

if($("p").find('a').length === 1){
   //perform operation
}

答案 3 :(得分:0)

效率不高,但这是我提出的最简洁,最好用(也是最好的)解决方案!

$('p').filter( function() {
    return !$('<p>'+$.trim($(this).html())+'</p>').contents().not('a:first').length;
}).addClass('solo');

http://jsfiddle.net/DYxgu/