我有一个包含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);
答案 0 :(得分:4)
尝试
var selection = document.getSelection(), // get selection
node = selection.anchorNode; // get containing 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
}
答案 1 :(得分:-1)
试试这个,
var a = document.getElementsByTagName('a');
while(a.length) {
var parent = a[ 0 ].parentNode;
while( a[ 0 ].firstChild ) {
parent.insertBefore( a[ 0 ].firstChild, a[ 0 ] );
}
parent.removeChild( a[ 0 ] );
}