2016-08-01 63 views
1

我有32個html元素,其ID名稱爲nyg,nyj和其他一些。我的目標是將mouseovermouseout事件綁定到每個元素,因此我可以更改用戶懸停的框的color。這不起作用,我相信有更好的方法來做到這一點,同時也是代碼效率。我正在爲32個不同的團隊做這件事,所以效率很重要。如果有人能帶領我走向正確的方向,我將不勝感激。謝謝!將獨立參數傳遞給.mouseover函數

HTML

<div id="content"> 
    <ul class="conference"> 
     <ul class="division"> 
     <li id="nyg" class="team"></li> 
     <li id="nyj" class="team"></li> 
     <li class="team"></li> 
     .... 

JS

var teams = [ 
{ 
    id: 'nyg', 
    name: 'Giants', 
    city: 'New York', 
    color1: '#000099', 
    color2: '#0000ff', 
    depth: 'http://www.ourlads.com/nfldepthcharts/depthchart/NYG', 
    offseason: 'http://espn.go.com/nfl/team/transactions/_/name/nyg', 
    logo: 'logos/nyg.jpeg' 
}, 
{ 
    id: 'nyj', 
    name: 'Jets', 
    city: 'New York', 
    color1: '#006600', 
    color2: '#009900', 
    depth: 'http://www.ourlads.com/nfldepthcharts/depthchart/NYG', 
    offseason: 'http://espn.go.com/nfl/team/transactions/_/name/nyg', 
    logo: 'logos/nyg.jpeg' 
}]; 

for (team in teams) { 
    $('#'+teams[team].id;).mouseover(mouseIn(teams[team].color1)).mouseout(mouseOut(teams[team].color2)); 
} 

function mouseIn(color) { 
    $(this).css("background-color", color); 
} 

function mouseOut(color) { 
    $(this).css("background-color", color); 
} 
+0

? :#my-id-one {background-color:#123456}; #my-id-one:hover {background-color:#654321}; –

回答

1

首先你的HTML是無效的。您不能將ul作爲ul的孩子 - 您需要在它們之間放置li

要真正解決您的問題,您可以將您的團隊數據修改爲一個對象,並使用li元素的id鍵,而不是一組對象。這樣,您可以直接訪問元素懸停時所需的對象。試試這個:在CSS

var teams = { 
 
    nyg: { 
 
    name: 'Giants', 
 
    city: 'New York', 
 
    color1: '#000099', 
 
    color2: '#0000ff', 
 
    depth: 'http://www.ourlads.com/nfldepthcharts/depthchart/NYG', 
 
    offseason: 'http://espn.go.com/nfl/team/transactions/_/name/nyg', 
 
    logo: 'logos/nyg.jpeg' 
 
    }, 
 
    nyj: { 
 
    name: 'Jets', 
 
    city: 'New York', 
 
    color1: '#006600', 
 
    color2: '#009900', 
 
    depth: 'http://www.ourlads.com/nfldepthcharts/depthchart/NYG', 
 
    offseason: 'http://espn.go.com/nfl/team/transactions/_/name/nyg', 
 
    logo: 'logos/nyg.jpeg' 
 
    } 
 
}; 
 

 
$('.team').hover(function() { 
 
    $(this).css('background-color', teams[this.id].color1); 
 
}, function() { 
 
    $(this).css('background-color', teams[this.id].color2); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="content"> 
 
    <ul class="conference"> 
 
    <li> 
 
     <ul class="division"> 
 
     <li id="nyg" class="team">NYG</li> 
 
     <li id="nyj" class="team">NYJ</li> 
 
     </ul> 
 
    </li> 
 
    </ul> 
 
</div>