找到一个特定的单词并用span标签包装

时间:2011-09-06 20:01:43

标签: javascript jquery

我不确定最好的办法。这是问题所在。我有一个菜单(列表项)具有不规则的显示模式。我不能直接改变html,因为它是从cms吐出来的。我希望如此,如果一个数组中的单词与链接中的单词匹配,那么该单词就会有一个跨度。 这是简化的代码:

<li class="item1"><a href="gosomewhere.html">About My Store</a></li>
<li class="item2"><a href="gosomewhereelse.html">Find Locations</a></li>

我想要的结果是:

<li class="item1"><a href="gosomewhere.html"><span class="bigwords">About My </span>Store</a></li>
<li class="item2"><a href="gosomewhere.html">Find <span class="bigwords">Locations</span></a></li>

我可以找到第一个单词:

      $(function() {
    $.fn.wrapStart = function (numWords) {
    var node = this.contents().filter(function () { return this.nodeType == 3 }).first(),
        text = node.text(),
        first = text.split(" ", numWords).join(" ");

    if (!node.length)
        return;

    node[0].nodeValue = text.slice(first.length);
    node.before('<span class="bigwords">' + first + '</span>');
};


$("li.item1 a").wrapStart(1);

但是,我想要做的是查看一个数组列表,并将我想要的那些特定单词包装在它们出现的任何位置。

数组就像是关于,存储,常见问题......

脚本会查找这些单词并将它们包装起来......

不确定如何解决这个问题。如果它更容易。因为大词只出现在开头或结尾但不在中间...我可以有另一个函数来寻找最后一个单词。

只有5个菜单项(不会改变),单词永远不会改变,这就是为什么我想只使用一个数组......

这是插件使用的输出:

<ul class="menu><li class="item-102 parent">
<a class="about" title="About my store" href="#">
<span class="bigwords">
<a xmlns="http://www.w3.org/1999/xhtml">About</a>
</span>
<a xmlns="http://www.w3.org/1999/xhtml"> my store</a>
</a>
</li></ul>

3 个答案:

答案 0 :(得分:4)

我最近写了一个简单的插件,可以做到这一点:

(它不再存在)

你会像这样使用它:

var arr = ["about my","locations"];
$.each(arr,function(i,word){
  $(".items").highlightText(word,"bigwords",true)
});

http://jsfiddle.net/4gtmH/23/

因为我正在使用正则表达式,所以你也可以这样做:

$(".items").highlightText("about my|locations","bigwords",true)

此外:

我使用.items作为一个类,因为在我的例子中,我给了ul一类项目。你可以提供任何选择器,它会突出显示元素中的所有文本及其子项。

以下是插件执行工作的部分,以防链接因某种原因而死亡:

$(this).find("*").andSelf().contents()

// filter to only text nodes that aren't already highlighted
.filter(function () {
    return this.nodeType === 3 && $(this).closest("." + hClass).length === 0;
})

// loop through each text node
.each(function () {
    var output;
    output = this.nodeValue.replace(re, "<" + defaultTagName + " class='" + hClass + "'>$1</" + defaultTagName + ">");
    if (output !== this.nodeValue) {
        $(this).wrap("<p></p>").parent()
            .html(output).contents().unwrap();
    }
});

答案 1 :(得分:0)

你看过这个jQuery plugin了吗?没有自己使用它,但看起来它很容易完成这项工作。

答案 2 :(得分:0)

你可以在所有元素上创建一个jquery选择器,并且foreach结果在选择器中设置val,并用val替换val和数据