如何将重复的jQuery代码整合到一个函数中?

jrh*_*man 4 css jquery

jQuery初学者在这里.

这是我正在做的事情.我有一个有10个热点的区域地图.将鼠标悬停在每个热点上,然后移动div的背景(id = dialpad)以显示其他数据(在精灵中).

我目前使用的代码,但我为每个热点ID都有一个单独的函数.

例如:

    $('#dial1')
    // On mouse over, move the background on hover
   .mouseover(function() {
     $('#dialpad').css('backgroundPosition', '0 -120px');
   })
   // On mouse out, move the background back
   .mouseout(function() {
     $('#dialpad').css('backgroundPosition', '0 0');
   })
     $('#dial2')
    // On mouse over, move the background on hover
   .mouseover(function() {
     $('#dialpad').css('backgroundPosition', '0 -240px');
   })
   // On mouse out, move the background back
   .mouseout(function() {
     $('#dialpad').css('backgroundPosition', '0 0');
   });
   ...
Run Code Online (Sandbox Code Playgroud)

我想要做的是将该代码合并到一个函数中,我只是从每个区域ID传递垂直偏移图.

有人可以帮忙吗?

use*_*716 5

$('#dial1,#dial2').hover(
    function() { changePosition('0 ' + (parseInt(this.id.match(/\d+$/)[0])) * -120 + 'px'); },
    function() { changePosition('0 0'); }
);

function changePosition(position) {
   $('#dialpad').css('backgroundPosition', position);
}
Run Code Online (Sandbox Code Playgroud)

更新:

或者,如果页面上的"热点"与索引号的顺序相同,那么您可以采用稍微更高效的方法并为它们提供所有类,并使用index属性.each()来确定正确的索引号.

$('.hotspots').each(function( idx ) {
    $(this).hover(
        function() { changePosition('0 ' + ((idx + 1) * -120) + 'px'); },
        function() { changePosition('0 0'); }
    );
});

function changePosition(position) {
   $('#dialpad').css('backgroundPosition', position);
}
Run Code Online (Sandbox Code Playgroud)

事实上,changePosition()如果你不想要它,你真的不需要这个功能.代码足够短,重复一点也不是什么大问题.

$('.hotspots').each(function( idx ) {
    $(this).hover(
        function() { $('#dialpad').css('backgroundPosition', '0 ' + ((idx + 1) * -120) + 'px')},
        function() { $('#dialpad').css('backgroundPosition', '0 0'); }
     );
});?
Run Code Online (Sandbox Code Playgroud)