JS-text节点模拟innerHTML属性

# [在线预览](https://jsfiddle.net/1010543618/mz7ybu8g/2/) text节点无innerHTML这个属性!!! 如果直接修改text节点的属性(data,nodeValue,textContent),或者使用js原生的修改text节点的内容的方法都会将HTML的预留字符变成转义字符直接显示成文本了,解决方法有: 1. 使用正则表达式找出pre的innerHTML字符串中的全部text节点的字符串进行修改 2. 给text外面包裹一个标签,改包裹标签的innerHTML,把包裹标签的内容移动到外面,删除包裹标签 3. 使用jquery的replaceWith方法,这个就非常严谨了 ``` replaceWith: function( value ) { var isFunc = jQuery.isFunction( value ); // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( !isFunc && typeof value !== "string" ) { value = jQuery( value ).not( this ).detach(); } return this.domManip( [ value ], true, function( elem ) { var next = this.nextSibling, parent = this.parentNode; if ( parent ) { jQuery( this ).remove(); parent.insertBefore( elem, next ); } }); }, ``` 例:将pre标签中的回车替换为\
,空格替换为\&ebsp;,制表符替换成双\&ebsp; ```html
d3.selectAll("circle").transition()
    .duration(750)
    .delay(function(d, i) { return i * 10; })
    .attr("r", function(d) { return Math.sqrt(d * scale); });

innerHTML of pre:

```

猜你喜欢

转载自www.cnblogs.com/jffun-blog/p/10206569.html