我正在尝试拆分包含html标签的字符串。
示例:的
var html = "The Company is in the business of <mark><i><b>[institutions contained herein.<mark><i><b>Parties Agreed.</b></i></mark>";
如果用户点击“派对”后面的div,他们最终应该使用不完整的html这两个变量:
"The Company is in the business of <mark><i><b>[institutions contained herein.<mark><i><b>Parties "
&安培;
Agreed.</b></i></mark>
我尝试使用这个:window.getSelection().anchorOffset
但是包含html标签,同时推断Offset并且split不会返回所需的字符串。
以下是div:
<div>The Company is in the business of<mark>[institutions contained herein.]</mark><i><b>Parties Agreed.</b></i></div>
JS:
var nodeText = $('div').html();
$('div').on('click', function(e) {
var userSelection = window.getSelection(),
start = userSelection.anchorOffset,
nodeBefore = nodeText.substr(0, start),
nodeAfter = nodeText.substr(start, nodeText.length);
console.log(nodeBefore);
console.log(nodeAfter)
});
当用户点击'b'或'mark'标签时,变量'start'没有返回准确的值,因此'nodeBefore'和'nodeAfter'也不准确。单击小提琴中的渲染文本,您将看到问题。