javascript - 如何在特定索引处的 div 内的文本子字符串周围添加 div 或 span?

标签 javascript html jquery css

我有一个包含字符串的 div。例如:

<div id='original'>A red chair that is on the left of another chair next to the door</div>

我已经在数据库中存储了一些用户选择的子字符串,并带有开始和结束索引。例如:

phrase: chair, start: 43, end: 48
phrase: the door, start: 58, end: 66

现在,我想在“原始”div 中的上述两个短语周围添加一个 span 或 div,以便突出显示这些短语。

预期结果:

<div id='original'>A red chair that is on the left of another <div style="display:inline; color:#ed3833; cursor:pointer;">chair</div> next to <div style="display:inline; color:#ed3833; cursor:pointer;">the door</div></div>

对于一个短语,我可以使用开始和结束索引在其周围插入 div,但对于后续插入,它显然会失败,因为由于在第一个短语周围添加了 div,索引现在已更改。你能帮我解决这个问题吗?

我不知道这是否有帮助,但为了在第一个短语周围添加 div,我使用以下逻辑:

str = $('#original').text()
var preStr = str.substring(0, startIdx);
var newStr = `<div style="display:inline; color:#ed3833; cursor:pointer;">${phrase}</div>`
var postStr = str.substring(endIdx, str.length);
result = preStr+newStr+postStr;

如果您需要更清晰的信息,请告诉我,我会尽力解释得更好。

最佳答案

您可以构建索引数组并执行以下操作:

var str = $('#original').html();

var startInd = [43, 58];
var lastInd = [48, 66];
var count = startInd.length;

for (let i = 0; i < count; i++) {
  let pre = str.substring(0, startInd[i]);
  let post = str.substring(lastInd[i], str.length);
  let phrase = str.substring(startInd[i], lastInd[i]);

  let nextPhrase;

  if (i < count - 1) {
    nextPhrase = str.substring(startInd[i + 1], lastInd[i + 1]);
  }

  str = pre + `<div style='display:inline; color:#ed3833; cursor:pointer;'>${phrase}</div>` + post;

  if (i < count - 1) {
    startInd[i + 1] = str.indexOf(nextPhrase, startInd[i + 1]) - 1;
    lastInd[i + 1] = startInd[i + 1] + nextPhrase.length;
  }

}

$('#original').html(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id='original'>A red chair that is on the left of another chair next to the door</div>

关于javascript - 如何在特定索引处的 div 内的文本子字符串周围添加 div 或 span?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63656188/

相关文章:

javascript - 如何在node js路由中调用外部函数

javascript - 如何在运行脚本之前等待页面完成所有内容的加载或如何最好地检测主要的 DOM 更改

jquery - 使用鼠标单击或鼠标悬停显示和隐藏内容

jQuery - 从属性获取文本

javascript - jQuery 在 div 上滚动

javascript - 使用 tr :nth-child(n) selector in a jQuery function

html - 响应式设计中不同尺寸元素之间的固定间距

javascript - 使用 jQuery 定位一组重复元素

jquery - 使用复选框的输入更改按钮的颜色

javascript - 类型的 React PropType 元素