2012-02-28 262 views
2

如何编写JS函数以删除点击范围内的范围并保留内部文本?如何删除span onclick或修改?

​<span class="test" onclick="removespan(this);">Data in red</span> 
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 
    ​removespan = function(e)​{ 
          alert(e.innerText); 
          }​ 
    CSS : ​span.test{color:red;} 

的onclick我想删除的跨度,只是保留了内部文本。 Infact我想有一个onmodify事件...删除跨度。 目的是在WYSIWYG编辑器中删除拼写检查跨度类。

+0

Is th span是其父节点中唯一的元素吗? – Diode 2012-02-28 05:49:03

回答

3

如果跨度为其父节点内唯一的子元素

<div> 
    <span class="test" onclick="removespan(this);">Data in red</span> 
</div> 


removespan = function(span) { 
    span.parentNode.innerHTML = span.innerHTML; 
} 

否则使用此功能

removespan = function(span) { 
    span.parentNode.replaceChild(document.createTextNode(span.innerHTML), span); 
} 
+0

+1第二选择! – 2012-02-28 06:17:35

0
<span id="test"></span> 

y=doc.getElementsById("test"); 

y.getParent().removeChild(y); 
1

如果有人有兴趣二极管的的“扩展版”第二种选择:

function removespan(span) { 
    // Get the text contents of the clicked span 
    var span_contents = span.innerHTML; 
    // Get the parent node of the clicked span 
    var span_parent = span.parentNode; 
    // Create a new text node in the DOM to hold the text contents 
    var text_node = document.createTextNode(span.innerHTML); 
    // Replace the clicked span node with your newly created text node 
    span_parent.replaceChild(text_node, span); 

    // Alternatively, do the above in one line... 
    // span.parentNode.replaceChild(document.createTextNode(span.innerHTML), span); 
}