<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>屬性解決變量污染</title>
<style type="text/css">
ul {
margin: 0;
padding: 0;
list-style: none;
}
li {
width: 80px;
height: 35px;
border-radius: 5px;
float: left;
margin-left: 3px;
}
</style>
</head>
<body>
<ul>
<li arg="10"></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
<script type="text/javascript">
// 學習目的:對象的(臨時)屬性可以幫助存儲臨時數據,因為臨時數據的生命周期往往很短.需要提示臨時數據的生命周期
// 臨時數據會隨屬性的消亡而消亡 | 被主動移除(delete)
var lis = document.querySelectorAll('li');
for (var i = 0; i < lis.length; i++) {
// lis[i]依次代表五個li頁面元素對象
// 給每一個li設置一個(臨時)屬性
lis[i].index = i; // 第一個li的index屬性存儲的就是索引0,以此類推,最后一個存儲的是索引4
lis[i].onclick = function () {
// var temp = lis[i].index; // lis[i]中的i一樣存在變量污染
var temp = this.index; // 當前被點擊的li
alert(temp) // temp => this.index(lis[i].index) => i(索引)
}
}
// 屬性的使用:****
</script>
<script type="text/javascript">
var lis = document.querySelectorAll('li');
console.log(lis); // 頁面元素集合
console.log(lis[0]); // 頁面元素
// 對象可以添加屬性與方法 | 萬物皆對象
lis.name = "元素集合";
console.log(lis.name); // lis => 是對象,頁面元素集合對象
lis[0].fn = function () {
console.log('li fn');
}
lis[0].fn(); // 每一個頁面元素都是對象
// 通過html方式給第一個li添加了一個全局屬性arg
console.log(lis[0].arg); // js無法直接獲取
// 總結:
// 1.js要使用頁面元素屬性,需要通過js手段給頁面對象手動添加屬性,添加的屬性不會渲染到html標簽中
// 2.通過html手動主動給標簽添加的全局屬性,js無法訪問,但是可以參與css布局
</script>
<style type="text/css">
li[arg="10"] {
background-color: orange;
}
</style>
</html>