1

我在块级标签中有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()

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

4

2 回答 2

0

这应该可以解决问题。替换$('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();
        }
    });
});
于 2013-10-05T19:01:40.643 回答
0

要隐藏它,您只需为 nomatch 类提供 CSS 属性 display:none。当您悬停或单击某处以查看更多上下文时,您可以添加一些 javascript 以使其淡入。

于 2013-10-05T17:57:16.927 回答