關(guān)于this的問題
for(var n=0;n<li.length;n++){//這步是相對于未被點(diǎn)擊部分的樣式
? ? ? ? ? ? ? ? li[n].className = "";
? ? ? ? ? ? ? ? div[n].className = "hide";
? ? ? ? ? ? ?}
下面這兩段代碼放到for遍歷上面為什么出錯,div[this.index]里的this指向的是誰?
? ? ? ? ? ? this.className = "on";//再對點(diǎn)擊事件添加相應(yīng)的屬性
? ? ? ? ? ? div[this.index].className = "";//通過之前的index編號綁定的指定div
?window.onload=function(){
? ? ? ? var tab = document.getElementById("tabs")
? ? ? ? var li = document.getElementsByTagName("li");
? ? ? ? var div = tab.getElementsByTagName("div");
? ? ? ? for(var i=0;i<li.length;i++){//獲取所有i編號的元素
? ? ? ? ? ? li[i].index = i; ?//定義一個index屬性對li進(jìn)行編號
? ? ? ? ? ??
? ? ? ? ? ? li[i].onclick = function(){
? ? ? ? ? ? ? ??
? ? ? ? ? ? for(var n=0;n<li.length;n++){//這步是相對于未被點(diǎn)擊部分的樣式
? ? ? ? ? ? ? ? li[n].className = "";
? ? ? ? ? ? ? ? div[n].className = "hide";
? ? ? ? ? ? ?}
? ? ? ? ? ? this.className = "on";//再對點(diǎn)擊事件添加相應(yīng)的屬性
? ? ? ? ? ? div[this.index].className = "";//通過之前的index編號綁定的指定div
? ? ? ? ? ? }
? ? ? ? }
? ? }
2016-12-09
不難看出,onclick 是在循環(huán)中確認(rèn)的,為了獲取這個循環(huán)中的數(shù)值,你需要用 index 來確認(rèn)你所點(diǎn)擊的標(biāo)簽的索引,如果你用 i 來作索引,那 i 的值只會為2。順帶一句?optionObject.index 是一種對象屬性。
2016-12-07
?? div[this.index].className = "";//通過之前的index編號綁定的指定div 這里的this呢?
2016-12-07
this指的就是這段代碼所在的那個節(jié)點(diǎn)。例如
上面通過li[i].onclick()來激活了for和this.className
那么this指的就是li[i]這個節(jié)點(diǎn),當(dāng)然,當(dāng)i為不同數(shù)的時候this指得也不同。
所以這里用this可以靈活的選中l(wèi)i中的每一個元素來實(shí)現(xiàn)效果,而不是唯一的素數(shù)。