innerHTML和innerText区别
innerText:拿到的是文本,如果文本里面有<>尖括号,不会把<>尖括号当成html元素解析
innerHTML:拿到的是文本,如果文本里面有<>尖括号,会把<>尖括号当成html元素解析
其实innerHTML和innerText获取到的都是文本,唯一的区别就是如果文本中有<>尖括号,innerText不会把<>尖括号当成html元素解析,而innerHTML会把<>尖括号当成html元素解析
接下来po一段代码案例和截图
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>javascript(json知识点)-测试json中包含尖括号和innerText和innerHTML知识点</title>
<script type="text/javascript">
//json字符串
var jsonStr1 = '{ "firstName":"令狐冲" , "lastName":"Doe" }';
//json对象
var jsonStr2 = {
"firstName" : "<font color=\"blue\">张无忌</font>",
"lastName" : "Doe"
};
window.onload = function() {
addTextToDiv1();
addTextToDiv2();
addTextToDiv3();
}
//添加文本到div节点中
function addTextToDiv1() {
//这种方式会直接把<>尖括号当成文本
var myTextNode = document.createTextNode(jsonStr2.firstName);
var divNode = document.getElementById("div1");
divNode.appendChild(myTextNode);
}
//添加文本到div节点中
function addTextToDiv2() {
var divNode = document.getElementById("div1");
divNode.innerText += jsonStr2.firstName;
console.log("innerText = " + divNode.innerText);
console.log("innerHTML = " + divNode.innerHTML);
}
//添加文本到div节点中
function addTextToDiv3() {
var divNode = document.getElementById("div1");
console.log("innerText = " + divNode.innerText);
console.log("innerHTML = " + divNode.innerHTML);
divNode.innerHTML += jsonStr2.firstName;
console.log("innerText = " + divNode.innerText);
console.log("innerHTML = " + divNode.innerHTML);
console.log("json对象的属性值 = " + jsonStr2.firstName);
}
function addMyText1(){
var div2Node = document.getElementById("div2");
div2Node.innerText = "<font color=\"red\">韦小宝</font>";
console.log("按钮1,innerText = " + div2Node.innerText);
}
function addMyText2(){
var div3Node = document.getElementById("div3");
div3Node.innerHTML = "<font color=\"red\">杨过</font>";
console.log("按钮2,innerHTML = " + div3Node.innerHTML);
}
function getValueByNode(){
console.log("innerText = " + document.getElementById("div2").innerText);
console.log("innerHTML = " + document.getElementById("div3").innerHTML);
}
/*
总结一下:
innerText 拿到的是浏览器解析执行后的html代码
innerHTML 拿到的是浏览器解析执行前的html代码
*/
</script>
</head>
<body>
<h1>javascript(json知识点)-测试json中包含尖括号和innerText和innerHTML知识点</h1>
<b>江西省赣州市于都县</b>
<font color="red">渡江大道66666号</font>
<div id="div1"></div>
<input type="button" value="按钮1-点击我,测试innerText" onclick="addMyText1()">
<input type="button" value="按钮2-点击我,测试innerHTML" onclick="addMyText2()">
<input type="button" value="按钮3" onclick="getValueByNode()">
<div id="div2"></div>
<div id="div3"></div>
</body>
</html>
/*
总结一下:
innerText 拿到的是浏览器解析执行后的html代码
innerHTML 拿到的是浏览器解析执行前的html代码
*/