我有一个包含 html 的可编辑 div:
"hello "<a href='#'>this is the title</a>" goodbye"
如果我只选择链接 html 的“他是”部分,然后运行:
document.execCommand('unlink');
标签分为两个标签离开:
<a href='#'>t</a>"his is"<a href='#'>the title</a>
有没有办法修改选择以扩展到整个链接标签以删除整个链接?
selection = document.getSelection() ?
更新
感谢盖比!我采用了他的解决方案并对其进行了一些修改,以扩展过去互换的粗体和斜体标签:
var selection = document.getSelection(); // get selection
var node = selection.anchorNode; // get containing node
var baseChild = function(parent, last) {
var children = parent.childNodes.length;
if (children == 0) {
return parent;
}
var child = (last == true) ? children-1 : 0;
return baseChild( parent.childNodes(child));
}
var findAndRemove = function(node) {
while (node && node.nodeName !== 'A'){ // find closest link - might be self
node = node.parentNode;
}
if (node){ // if link found
var range = document.createRange(); //create a new range
range.selectNodeContents(node); // set range to content of link
selection.addRange(range); // change the selection to the link
document.execCommand('unlink'); // unlink it
if ( node.previousSibling ){
findAndRemove(baseChild(node.previousSibling, true));
}
if ( node.nextSibling ){
findAndRemove(baseChild(node.nextSibling, false ));
}
}
}
findAndRemove(node);