1

我会使用 jquery 来查找 ap 标签中强标签的每个实例,并像这样向 p 标签添加一个类:

<p><strong>Bold Text</strong></p>

会变成

<p class="hasStrong"><strong>Bold Text</strong></p>

我不确定实现这一点的最佳方法,这里有一个镜头:

$("p").find("strong").parent("p").addClass("hasStrong");

这可行,但我希望它选择只有强标签的段落,没有别的。所以这不会应用该类:

<p><strong>Bold Text</strong> Here is some more text</p>

我将如何使用 jQuery 来做到这一点?

4

6 回答 6

4
$('p:has(strong)').filter(function(){
    return $(this).contents().length === 1;
}).addClass('hasStrong');

http://jsfiddle.net/vbzkt/

于 2013-02-15T15:12:37.560 回答
3
$('p').filter(function(){
     return $(this).text() == $(this).find('strong').text();
}).addClass('yourclass');
于 2013-02-15T15:10:18.313 回答
2

用 jQuery 选择文本节点并不容易。如果您不需要这样做,这会容易得多。

但是,您仍然可以通过使用.contents来检查文本节点长度来做到这一点。

$("p").find("strong:only-child").each(function () {
    var $p = $(this).closest('p');
    if ($p.contents().length === 1) {
        $p.addClass('hasStrong');
    }
});

:only-child方法非常适合从一开始就仅过滤出合格的节点,但并非严格要求。请注意,这也会突出显示<strong>包含子项的内容。如果您不想这样做,只需检查$(this)回调中没有子项。

于 2013-02-15T15:10:57.583 回答
2

仅选择p具有一个或多个strong标签且没有文本节点的标签:

$('p').filter(function() {
    return $('strong', this).length == this.childNodes.length;
}).addClass('hasStrong');

小提琴

于 2013-02-15T15:15:59.150 回答
1

这是另一个考虑文本节点的解决方案:

$("p").filter( function() {
    return this.childNodes.length === 1 && $( 'strong', this ).length;
} ).addClass("hasStrong");

演示:http: //jsfiddle.net/vDfV5/

于 2013-02-15T15:12:38.393 回答
-3

您可以通过向下钻取然后使用“parent()”将类添加到 strongs 父级来做到这一点。

$("p").children("strong").parent().addClass("hasStrong");

于 2013-02-15T15:10:17.020 回答