jQuery简化代码(初学者)

jQuery简化代码(初学者),jquery,simplify,hoverintent,Jquery,Simplify,Hoverintent,我开始熟悉jQuery,但发现自己一遍又一遍地重复代码 当然有一种更简单的方法来写这个: $('#more-mcr, #more-hilton, #more-lpool').hide(); $('#mcr-hatters').hoverIntent(function() { $('#mcr-hilton').stop().animate({opacity: 0.4}); $('#more-mcr').fadeIn({duration:200}); }, function()

我开始熟悉jQuery,但发现自己一遍又一遍地重复代码

当然有一种更简单的方法来写这个:

$('#more-mcr, #more-hilton, #more-lpool').hide();


$('#mcr-hatters').hoverIntent(function() {
    $('#mcr-hilton').stop().animate({opacity: 0.4});
    $('#more-mcr').fadeIn({duration:200});
}, function() {
    $('#mcr-hilton').stop().animate({opacity: 1});
    $('#more-mcr').fadeOut({duration:200});
});

$('#mcr-hilton').hoverIntent(function() {
    $('#mcr-hatters').stop().animate({opacity: 0.4});
    $('#more-hilton').fadeIn({duration:200});
}, function() {
    $('#mcr-hatters').stop().animate({opacity: 1});
    $('#more-hilton').fadeOut({duration:200});
});

$('#lpool-hostel').hoverIntent(function() {
    $('#more-lpool').fadeIn({duration:200});
}, function() {
    $('#more-lpool').fadeOut({duration:200});
});

$('#offers-mcr').hoverIntent(function() {
    $('#offers-lpool').stop().animate({opacity: 0.4});
    $('#offers-bham').stop().animate({opacity: 0.4});
}, function() {
    $('#offers-lpool').stop().animate({opacity: 1});
    $('#offers-bham').stop().animate({opacity: 1});
});

$('#offers-lpool').hoverIntent(function() {
    $('#offers-mcr').stop().animate({opacity: 0.4});
    $('#offers-bham').stop().animate({opacity: 0.4});
}, function() {
    $('#offers-mcr').stop().animate({opacity: 1});
    $('#offers-bham').stop().animate({opacity: 1});
});

$('#offers-bham').hoverIntent(function() {
    $('#offers-lpool').stop().animate({opacity: 0.4});
    $('#offers-mcr').stop().animate({opacity: 0.4});
}, function() {
    $('#offers-lpool').stop().animate({opacity: 1});
    $('#offers-mcr').stop().animate({opacity: 1});
});

我还想为hoverIntent设置延迟,但我认为目前编写代码的方式不可能做到这一点…?

向要悬停的各种项目添加一个类,例如
hoverItem
。然后可以使用
$('.hoverItem').hoverIntent(function()…)
一次设置多个项目。鉴于您给出的示例中定义了两个不同的不透明性,我将创建两个类。

您可以创建一个命名函数(例如函数myHover(){}),然后在
中.hoverIntent
将其引用为
.hoverIntent(myHover)
。另外,考虑使用两个IDS具有相同的附加函数时的使用。

如果有很多相同的项,两个类可能工作,但是如果它将停留在这几点,则ID选择器可能会更快。