将唯一标识符添加到所选文本的HTML标签

3

我有一个函数能够获取内容中选中的文本,但是我想要的是在该文本所属的HTML标签中加入一个唯一的ID。

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection();
    } else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}
 $('#outline').on('click',function(){
       var text = getSelectedText();
//here want to add the unique id to this paragraph that contains this text
});

我遇到了麻烦,找不到类似的解决方案。


@JuniorCompressor,问题不在于唯一标识符,而在于如何获取所选文本的HTML内容。 - Laureta Xhaferraj
好的...但无论如何请检查一下它是否有帮助。 - JuniorCompressor
好的,谢谢。您需要帮忙处理选定文本的HTML吗? - Laureta Xhaferraj
2
看了一下 https://dev59.com/m2w05IYBdhLWcg3wfhyg。当你找到所选文本的父元素后,完成这个任务应该很容易。 - Filip Krstic
显示剩余2条评论
1个回答

0
这是一个你想要做的例子。
演示:https://jsfiddle.net/xo01kxLa/1/
function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection();
    } else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}
function getSelectionParentElement() {
    var parentEl = null, sel;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            parentEl = sel.getRangeAt(0).commonAncestorContainer;
            if (parentEl.nodeType != 1) {
                parentEl = parentEl.parentNode;
            }
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        parentEl = sel.createRange().parentElement();
    }
    return parentEl;
}
$('#outline').on('click', function () {
    var text = getSelectedText();
    var parent = getSelectionParentElement();
    $(parent).attr('id', 'id' + Math.floor((Math.random() * 1000) + 1));
});

如果您只想设置唯一标识一次,那么请将其设置为:
$('#outline').on('click', function () {
    var text = getSelectedText();
    var parent = getSelectionParentElement();
    if($(parent).attd('id') != '') {
            $(parent).attr('id', 'id' + Math.floor((Math.random() * 1000) + 1));
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接