jquery或php在块内包装,但排除span


jquery or php wrap inside block but exclude span

>我在块级标签中有html;我的搜索结果在标签中用匹配项包装句子,如下所示:

<p>
Some text. More text. <span class=match>Sentence with match.</span> More text.
</p>

我的目标是隐藏(而不是删除(不匹配的文本。我认为最有效的方法是包装不匹配的文本并对其进行 css 样式:

<p>
<span class=nomatch>Some text. More text. </span><span class=match>Sentence with match.</span><span class=nomatch> More text.</span>
</p>

有点倒置包装。但是我该怎么做呢?我可以使用jquery或php,但它必须是DOM安全的,并且段落可能是任何块元素。

所以像这样的东西(这是编造的(:

$('.match').wrapOutside()

编辑:我认为人们是对的,我需要在我用来标记匹配的相同代码中进行"nomatch"标记。

要隐藏它,你可以给nomatch类提供CSS属性display:none。你可以加入一些javascript,让它在你悬停或点击某处时淡入,也可以查看更多上下文。

这应该可以解决问题。将$('p')替换为所需的任何选择器。

$('p').each(function() {
    $.each(this.childNodes, function(i, child) {
        if (child.nodeType == 3) { // text node
            $(child).before(
                $('<span class="nomatch"></span>').text(child.data)
            ).remove();
        }
    });
});