将独立参数传递给.mouseover函数



我有32个html元素,id名称分别为nygnyj和其他一些元素。我的目标是将mouseovermouseout事件绑定到每个元素,这样我就可以更改用户悬停在其上的框的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);
}

首先,您的HTML无效。不能将ul作为ul的子级,需要将li放置在它们之间。

为了实际解决您的问题,您可以将团队数据修改为一个对象,由li元素的id键控,而不是一个对象数组。这样,您就可以在悬停元素时直接访问所需的对象。试试这个:

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>

最新更新