找到一个特定的单词并用span标签换行
find a specific word and wrap with a span tag
我不知道该怎么做。问题来了。我有一个显示模式不规则的菜单(列表项)。我不能直接改变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
相关文章:
- 使用Clipboard.js复制span文本
- 当鼠标悬停在文本中的单词上时显示警报
- 使用 JavaScript split 来包含单词,标点符号与 span 但忽略 HTML
- 选择 h2 标签的前两个单词并换行 span 标签
- 如何在单词周围添加 span 元素
- 将鼠标悬停在某个单词上时显示span,并根据需要进行替换
- 在jquery中获取span标记的前2个单词和后2个单词
- JavaScript:如何用包含唯一id的span标记将字符串中的每个单词包装起来
- 如何将元素的每个单词包装在 span 标记中
- Javascript:在字符串的最后两个单词周围span
- Regex将所有单词换行到span中,不包括img元素
- 如何用jQuery在span标签中换行文本,除了第一个单词
- 使用regexp添加一个特定单词的span类
- 将每个单词的第一个字母包装在span标签- javascript中
- 不区分大小写,查找单词并将其换行到span中
- 找到一个特定的单词并用span标签换行
- 如果术语表中有定义,使用SPAN更改单词的颜色
- 如果元素包含这些单词中的任何一个,则将该单词包装在 span 中
- 在javascript中,在单词边界的span标签中包装每个单词的正则表达式
- 获取每个span的最后一个单词的首字母