我有一些文字:
<p>hello world. This is a test paragraph.</p>
Run Code Online (Sandbox Code Playgroud)
我想<em>在开始位置和</em>结束位置添加一个标签给我们:
<p>
<em>hello</em> world. This is a <em>test</em> paragraph.
</p>
Run Code Online (Sandbox Code Playgroud)
我有一个开始和结束位置的列表
<lst name="offsets">
<int name="start">0</int>
<int name="end">5</int>
<int name="start">22</int>
<int name="end">27</int>
</lst>
Run Code Online (Sandbox Code Playgroud)
有没有简单的方法来做到这一点?
这是我的做法(对答案略有修改):
var p = doc+=" "//document.querySelector("#content"),//I added a space to the end of the document because if we try to wrap the em tags around the word we are looking for and it is at the end of the document then it gives us undefined.
textArray = p.split('');
//offsets = [{ start: 0, end: 5 }, { start: 22, end: 27 }];
offsets.forEach(function (offset) {
textArray[offset.start] = '<em>' + textArray[offset.start];
textArray[offset.end] = '</em>' + textArray[offset.end];
});
document.querySelector("#content").innerHTML += textArray.join('');
document.querySelector("#content").innerHTML += "<hr>";
Run Code Online (Sandbox Code Playgroud)
这是一个不需要 jQuery 的简单示例。
从一offset组对象开始以确定start/end值。
[
{ start: 0, end: 5 },
{ start: 22, end: 27 }
]
Run Code Online (Sandbox Code Playgroud)
然后遍历offset数组:
[
{ start: 0, end: 5 },
{ start: 22, end: 27 }
]
Run Code Online (Sandbox Code Playgroud)
var p = document.querySelector('p'),
textArray = p.innerText.split(''),
offsets = [{ start: 0, end: 5 }, { start: 22, end: 27 }];
offsets.forEach(function (offset) {
textArray[offset.start] = '<em>' + textArray[offset.start];
textArray[offset.end] = '</em>' + textArray[offset.end];
});
p.innerHTML = textArray.join('');Run Code Online (Sandbox Code Playgroud)
如果您想解析列表元素以创建offset数组:
<p>hello world. This is a test paragraph.</p>Run Code Online (Sandbox Code Playgroud)
var p = document.querySelector('p'),
textArray = p.innerText.split(''),
offsets = [];
Array.prototype.forEach.call(document.querySelectorAll('lst > int[name="start"]'), function (el) {
offsets.push({start: el.innerText, end: el.nextElementSibling.innerText});
});
offsets.forEach(function (offset) {
textArray[offset.start] = '<em>' + textArray[offset.start];
textArray[offset.end] = '</em>' + textArray[offset.end];
});
p.innerHTML = textArray.join('');Run Code Online (Sandbox Code Playgroud)