我想使用带有背景颜色的跨度突出显示(或"注释")div中的几个单词。
在我的(最小)示例中,单词" x"和" y"应该注释(y的位置是37,x的位置是44)。但是,我的方法" annotateString"似乎不起作用,但我不知道为什么......
我的方法的想法是迭代div html内容,在所需位置添加span前缀或后缀。由于这个事实,我给出了基于字符串的位置,而不是因为先前的注释修改了html内容,我想要位置指针" pos"如果它在html元素内部(f.ex.已经存在跨度)冻结。
function annotateString(str, start, end, prefix, suffix) {
var annotatedString = '';
var pos = -1;
var freeze = false;
if (str[0] == '<') {
freeze = true;
}
for (var i = 0; i < str.length; i++) {
if (!freeze && str[i] != '<')
pos++;
if (str[i] == '<')
freeze = true;
if (str[i] == '>')
freeze = false;
if (pos == start && !freeze)
annotatedString += prefix + str[i];
else if (pos + 1 == end && !freeze)
annotatedString += str[i] + suffix;
else
annotatedString += str[i];
}
return annotatedString;
}
$(function() {
var strOld = $("#item").html();
var prefix = '<span style="background-color:yellow;">';
var suffix = '</span>';
// this should annotate the "y"
var strNew = annotateString(strOld, 37, 37, prefix, suffix);
$("#item").html(strNew);
// this should annotate the "x"
var strOld = $("#item").html();
var strNew = annotateString(strOld, 44, 44, prefix, suffix);
$("#item").html(strNew);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item">In this string I want to annotate "y" <- "x"</div>
&#13;
答案 0 :(得分:0)
我有三个错误需要处理
<
,我已将其替换为<
if (pos + 1 == end)
所以我最终得到了另一种解决方案,我认为代码是自我解释的!
function annotateString(str, start, end, prefix, suffix) {
var annotatedString = '';
var pos = -1;
var freeze = false;
if (str[0] == '<') {
freeze = true;
}
for (var i = 0; i < str.length; i++) {
if (!freeze && str[i] != '<')
pos++;
if (str[i] == '<')
freeze = true;
if (str[i] == '>')
freeze = false;
// -------------------------------------- prefix on start
if (pos == start && !freeze)
annotatedString += prefix;
// --------------------------------------- content anyway
annotatedString += str[i];
// ---------------------------------------- suffix on end
if (pos == end && !freeze)
annotatedString += suffix;
}
return annotatedString;
}
$(function() {
var strOld = $("#item").html();
var prefix = '<span style="background-color:yellow;">';
var suffix = '</span>';
// this should annotate the "y"
var strNew = annotateString(strOld, 35, 35, prefix, suffix);
$("#item").html(strNew);
// this should annotate the "x"
strOld = $("#item").html();
strNew = annotateString(strOld, 45, 45, prefix, suffix);
$("#item").html(strNew);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item">In this string I want to annotate "y" <- "x"</div>
此外,由于您仔细检查freeze
字符,因此无需将<
变量初始化为true,但这只是代码审核