编写这个jQuery函数的更好方法是什么?

时间:2010-12-21 07:22:40

标签: javascript jquery function

基本上我试图减少一些代码,但我不知道该怎么做,我有9个DIV的所有绝对定位在不同的位置。他们都是格雷,但是当徘徊在徘徊的DIV时,淡出并相应的DIV消失。是否有更好的方式来写这个?

$('#l1').hover(function () {
    $(this).fadeOut('300');
    $('#l1c').fadeIn('300')
});
$('#l2').hover(function () {
    $(this).fadeOut('300');
    $('#l2c').fadeIn('300')
});
$('#l3').hover(function () {
    $(this).fadeOut('300');
    $('#l3c').fadeIn('300')
});
$('#l4').hover(function () {
    $(this).fadeOut('300');
    $('#l4c').fadeIn('300')
});
$('#l5').hover(function () {
    $(this).fadeOut('300');
    $('#l5c').fadeIn('300')
});
$('#l6').hover(function () {
    $(this).fadeOut('300');
    $('#l6c').fadeIn('300')
});
$('#l7').hover(function () {
    $(this).fadeOut('300');
    $('#l7c').fadeIn('300')
});
$('#l7').hover(function () {
    $(this).fadeOut('300');
    $('#l7c').fadeIn('300')
});
$('#l1c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l1').fadeIn('300')
});
$('#l2c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l2').fadeIn('300')
});
$('#l3c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l3').fadeIn('300')
});
$('#l4c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l4').fadeIn('300')
});
$('#l5c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l5').fadeIn('300')
});
$('#l6c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l6').fadeIn('300')
});
$('#l7c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l7').fadeIn('300')
});

2 个答案:

答案 0 :(得分:6)

$('#l1,#l2,#l3,#l4,#l5,#l6,#l7').hover(function() {
    $(this).fadeOut(300);
    $("#" + this.id + "c").fadeIn(300);
});

$('#l1c,#l2c,#l3c,#l4c,#l5c,#l6c,#l7c').mouseout(function() {
    $(this).fadeOut(300);
    $("#" + this.id.substring(0, this.id.length - 1)).fadeIn(300);
});

答案 1 :(得分:1)

您可以为两种类型的div添加两个类。例如:对于#l1到#l7,添加类“.ln”;对于#l1c到#l7c,添加类“.lnc”,然后使用下面的代码:

$(".ln").live("hover", function(){
  $(this).fadeOut('300');
  $("#" + $(this).attr("id") + "c").fadeIn(300);
};

$(".lnc").live("mouseout", function(){
  var id = $(this).attr("id");
  $(this).fadeOut('300');
  $("#" + id.substring(0, id.length - 1)).fadeIn(300);
};
相关问题