我有32个html元素,ID名称为nyg
,nyj
,还有其他一些。我的目标是将mouseover
和mouseout
事件绑定到每个元素,这样我就可以更改用户悬停的框的color
。这不起作用,我相信有更好的方法来做到这一点,同时也是代码有效。我为32个不同的团队做这个,所以效率很重要。如果有人能引导我朝着正确的方向前进,我会非常感激。谢谢!
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 :(得分:1)
首先,您的HTML无效。您不能ul
作为ul
的孩子 - 您需要在li
之间放置id
。
要真正解决您的问题,您可以将团队数据修改为一个对象,由li
元素的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>
%link(rel="canonical" href="current_page.data.canonical")