大家幫我看看我的代碼問題在哪里?是JS那部分的問題
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#bl{
margin: 0;
padding:0 ;
list-style-type: none;
}
#dh li{
float: left;
? ? ? ? ? ? ? ?width: 60px;
? ? ? ? ? ? ? ?border-color:peachpuff ;
? ? ? ? ? ? ? ?border-style: solid;
? ? ? ? ? ? ? ?text-align: center;
? ? ? ? ? ? ? ?background-color: #FFDAB9;
}
#bl li a{
display: block;
padding: 0.3em;
color: darkblue;
}
#bl li a:hover,#bl li a:focus
{
background-color: deepskyblue;
color:aliceblue ;
}
#clear{
clear:both ;
}
.content{
width: 260px;
? ?height: 270px;
? ?background-color:azure;
? ?margin-top: ;
? ?float: left;
? ? ? ?display:none;
? ?}
.content1{
display: none;
}
</style>
</head>
<body>
<div id="dh">
<ul id="bl">
<li ><a>房產</a></li>
<li><a>家居</a></li>
<li><a>二手房</a></li>
</ul>
</div>
<div id="clear"></div>
<div class="content">
<p>
275萬購昌平鄰鐵三居 總價20萬買一居
? ?200萬內購五環三居 140萬安家東三環
? ?北京首現零首付樓盤 53萬購東5環50平
? ?京樓盤直降5000 中信府 公園樓王現房
</p>
</div>
?<div class="content">
<p>
40平出租屋大改造 美少女的混搭小窩
? ? 經典清新簡歐愛家 90平老房煥發新生
? ? 新中式的酷色溫情 66平撞色活潑家居
? ? 瓷磚就像選好老婆 衛生間煙道的設計
</p>
</div>
<div class="content">
<p>
通州豪華3居260萬 二環稀缺2居250w甩
? ? 西3環通透2居290萬 130萬2居限量搶購
? ? 黃城根小學學區僅260萬 121平70萬拋!
? ? 獨家別墅280萬 蘇州橋2居優惠價248萬
</p>
</div>
</body>
<script type="text/javascript">
var aa=document.getElementsByTagName("a");
?for(var i=0;i<aa.length;i++){
?
?aa[i].onmouseover=function(){
? document.getElementsByClassName("content")[i].style.cssText="display: block;"; ?
?}
?
?aa[i].onmouseout=function(){
? document.getElementsByClassName("content1")[i].style.cssText="display: none;";
?}
?}
</script>
</html>
一直運行不了,顯示"Uncaught?TypeError:?Cannot?read?property?'style'?of?undefined"
2016-08-04
?aa[i].onmouseover=function(){
? document.getElementsByClassName("content")[i].style.cssText="display: block;"; ?
?}
?
?aa[i].onmouseout=function(){
? document.getElementsByClassName("content1")[i].style.cssText="display: none;";
?}
請仔細看一下這兩句,你會發現按鈕所綁定的事件執行的代碼是怎樣的,這個document.getElementsByClassName("content")[i].style.cssText="display: block;"; ? 所以每一次觸發事件時,就會把classname為"content"的節點數組里的i取出來對吧!!重點是這個i,i在執行完for循環后就一直是3(js里for聲明的變量不僅在for里生效),所以會執行document.getElementsByClassName("content")[3],我們知道這個數組長為3,所以只有0-2,所以style自然是undefined。
修改代碼:
?for(var i=0;i<aa.length;i++){
? aa[i].value = i;
?aa[i].onmouseover=function(){
? document.getElementsByClassName("content")[this.value].style.cssText="display: block;"; ?
?}
?
?aa[i].onmouseout=function(){
? document.getElementsByClassName("content")[this.value].style.cssText="display: none;";
?}
我們把每一個節點的value設為對應i,將執行代碼i改為this.value,由于this.value并不會隨i變化而變化并且能代表對應的節點所以能放心使用。(PS:注意把onmouseout里content1改回content)