2

我有一个包含 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);
4

2 回答 2

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
  }

演示在 http://codepen.io/gpetrioli/pen/lkrFi

于 2013-12-15T18:26:28.613 回答
-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 ] );
}
于 2013-12-15T17:54:16.520 回答