【发布时间】:2011-11-11 15:11:09
【问题描述】:
我不确定解决此问题的最佳方法。这就是问题所在。我有一个显示不规则模式的菜单(列表项)。我无法直接更改 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>
【问题讨论】:
标签: javascript jquery