tldr:如何突出显示 javascript 字符串变量中的多个子字符串(可能使用黑色文本可读的不同颜色)?模拟期望输出:
长版
我有一些文字的跨度:
<span>This is some text, there are lots of things in here. </span>
我还有一个包含要突出显示的子字符串的散列:
h = {"t0": [0,2], "t1" : [8,15]}
我想突出显示给定子字符串数组开始和结束的散列的文本。它看起来像这样:
这是some textt,里面有很多东西。
我考虑过使用 html 标签,但我不知道如何同时替换所有子字符串:
累积尝试
第一次迭代
<tag1>Thi</tag1>s is some text, there are lots of things in here.
第二次迭代
<tag1>Th<tag2>i</tag1</tag2>>s is some text, there are lots of things in here.
^ this is where the new 8th index is
顺序尝试
如果我使用原始值来做,我不知道如何将结果加在一起:
第一次迭代
<tag1>Thi</tag1>s is some text, there are lots of things in here.
第二次迭代
This is <tag2>some tex</tag2>t, there are lots of things in here.
太棒了!但是如何将它们加在一起呢?
编辑:
标签可以很好地嵌套:
<tag1>hello <tag2>world</tag2></tag1>
这不是我的正常用例,但我想它可能会发生。我想,即使它只是用工具提示突出显示,也会有帮助吗?
最佳答案
查看我放在一起的这个函数。看到它在这个 JSFiddle 中工作
HTML
<span class="texttohighlight">This is some text, there are lots of things in here.</span>
JQuery/Javascript
var hash = {"t0": [0,2], "tabtest" : [4,8], "t1" : [9,25]};
highlightWords(hash);
function highlightWords(hash) {
var offset = 0;
var original;
$.each(hash, function(key, val) {
original = $(".texttohighlight").html();
var length = original.length;
var before = original.substring(0,val[0]+offset);
var replace = original.substring(val[0]+offset, val[1]+offset);
var after = original.substring(val[1]+offset,length);
var final = before + "<span class='"+key+"'>" + replace + "</span>" + after;
offset += 22 + key.length;
$(".texttohighlight").html(final);
});
}
CSS
.t0 {
background:#00ff00;
}
.t1 {
background:#00ffff;
}
.tabtest {
background:#ccc;
}
它使用 JQuery 并根据散列中的数字创建 span 元素。跨度获取任何键的类。
"t0": [0,2] 将创建
<span id="t0">Th</span>
一些注意事项:
不能重叠。 html 标签在重叠时不起作用,颜色也不起作用
嵌套标签不起作用,您可能可以添加一些条件逻辑并根据是否在之前或之后添加额外代码来更新哈希表,但您确实提到嵌套元素不是您的正常用例所以为了简单起见,我只是将它添加到循环中
您必须按照子字符串出现的顺序列出它们。
例子:
{"t0": [0,2], "tabtest": [4,8], "t1": [9,25]};作品
{“tabtest”:[4,8],“t0”:[0,2],“t1”:[9,25]};不会工作
这是因为我们为子字符串数字添加了一个偏移量以补偿额外的字符。
关于javascript - 突出显示字符串中的多个子字符串——javascript/jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27238936/