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