jquery - 添加唯一的 id 到选定的文本 html 标签

标签 jquery textselection

我有一个函数可以获取内容的选定文本,但我想要做的是获取此选定文本,并向其 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
});

我被困住了,在其他地方找不到类似的东西。

最佳答案

这是您想要执行的操作的示例。

演示: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));
});

如果您只想设置一次唯一 ID,请设置:

$('#outline').on('click', function () {
    var text = getSelectedText();
    var parent = getSelectionParentElement();
    if($(parent).attd('id') != '') {
            $(parent).attr('id', 'id' + Math.floor((Math.random() * 1000) + 1));
    }
});

关于jquery - 添加唯一的 id 到选定的文本 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29208673/

相关文章:

javascript - 使用我自己的 javascript 功能包装第 3 方 Web 应用程序

javascript - 搜索在 jquery 自动完成中不起作用

javascript - 禁用其他点击图像

javascript - 查找与所选文本匹配的 DOM 选择器集

javascript - 计算文本选择的 xy 位置

jquery - Smalltalk Seaside 键入时进行 jQuery 搜索

php - 如何找到修改了哪个输入字段?

textarea - 如何知道用户在 JavaFX TextArea 中选择了哪个文本字符串

ios - 当用户在 iOS 11 中点击时,UItextview 选择的文本不会被取消选择

eclipse-plugin - Eclipse 插件 :TextSelection cannot resoleve