找到一个特定的单词并用span标签换行

find a specific word and wrap with a span tag

本文关键字:单词 span 换行 标签 一个      更新时间:2023-09-26

我不知道该怎么做。问题来了。我有一个显示模式不规则的菜单(列表项)。我不能直接改变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);

然而,我想做的是查看数组列表,并将我想要的特定单词换行到它们出现的任何位置。

数组应该是about, store, faq…

脚本将查找这些单词并将其换行…

我不知道该怎么做。如果更容易的话。因为大词只出现在开头或结尾,而不在中间……我可以有另一个函数来查找最后一个单词。

只有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>

我最近写了一个简单的插件,可以完成这个任务:

(已不存在)

你可以这样使用:

var arr = ["about my","locations"];
$.each(arr,function(i,word){
  $(".items").highlightText(word,"bigwords",true)
});
http://jsfiddle.net/4gtmH/23/

因为我使用regexp,你也可以这样做:

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

:

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

这是插件的工作部分,以防链接由于某种原因而失效:

$(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();
    }
});

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

您可以在所有元素上创建一个jquery选择器,并在选择器中为每个结果设置val,将val替换为data