jquery中的html()函数不会把undefined添加到标签中
js中的innerHTML会把undefined添加到标签中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>javascript中innerHTML和jquery中的html(undefined)函数在处理undefined时的区别</title>
<link rel="stylesheet" type="text/css" href="inputAndDiv.css">
<style type="text/css">
input[type=submit] {
background-color: red;
border: 0px solid red;
color: #fff;
}
</style>
</head>
<body style="background-color: #CCE8CF;">
<h3 style="color: #cd1636;">
javascript中innerHTML和jquery中的html(undefined)函数在处理undefined时的区别
</h3>
<p id="test">hello</p>
<ul><li id="test2"></li></ul>
<p id="p1"></p>
<p id="p2"></p>
</body>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
console.log(typeof '江西省赣州市于都县'); //结果为string
$('#test').html('江西省赣州市于都县');
console.log(typeof undefined);//结果为undefined
$('#test').html(undefined); //并不会覆盖
var a;
console.log(typeof a);//结果为undefined
$('#test2').html(a); //不会把undefined添加到li标签中
// console.log(typeof undefined);//结果为undefined
// $('#test2').html(undefined); //不会把undefined添加到li标签中
// function b(){
// }
// console.log(typeof b());//结果为undefined
// $('#test2').html(b()); //不会把undefined添加到li标签中
var arr = ['红红火火恍恍惚惚'];
console.log(typeof arr);//结果为object
$('#test2').html(arr);//会把红红火火恍恍惚惚添加到li标签中
// console.log(typeof arr.shift());//结果为undefined
// $('#test2').html(arr.shift()); //不会把undefined添加到li标签中
// var arr2 = ['张三', '李四'];
// console.log(typeof arr2);//结果为object
// $('#test2').html(arr2);//会把张三李四添加到li标签中
//定义一个空的数组对象(即数组对象中没有任何元素,元素个数为0)
var arr3 = [];
console.log(typeof arr3);//结果为object
$('#test2').html(arr3);//会把li标签中的原来内容覆盖掉
var testVar = 666;
console.log(testVar);
testVar = undefined;
console.log(testVar);//会覆盖
var testVar = undefined;
console.log(testVar);//会覆盖
var testVar = 888;
console.log(testVar);//会覆盖
testVar = 55;
console.log(testVar);//会覆盖
console.log('***************************');
var numbers = [25, 34, 76];
var count = numbers.length;
//测试看看在循环中会不会把undefined添加到p标签中
for (var i = 0; i < count + 1; i++) {
var val = numbers.shift();
console.log(val);
//js中的innerHTML会把undefined添加到p标签中
document.getElementById('p1').innerHTML = undefined;
$('#p1')[0].innerHTML = undefined;
$('#p1').get(0).innerHTML = undefined;
//jquery中的html()函数不会把undefined添加到p标签中
//如果val变量的值是undefined,不会把undefined添加到p标签中
$('#p1').html(val);
}
$('#p2').each(function() {
//jquery中的html()函数不会把undefined添加到p标签中
$('#p2').html(undefined);
//jquery中的html()函数不会把undefined添加到p标签中
$(this).html(undefined);
//js中的innerHTML会把undefined添加到p标签中
// document.getElementById('p2').innerHTML = undefined;
//js中的innerHTML会把undefined添加到p标签中
// this.innerHTML = undefined;
});
</script>
</html>