2009-07-29 4 views
1

Je travaille avec un code jquery très basique et je voudrais condenser ce que j'ai fait en une fonction avec des paramètres passés.JQuery, Passing Parameters

J'ai quelques-unes:

$(".about").hover(function() { 
    $(this).attr("src","_img/nav/about_over.gif"); 
     }, function() { 
    $(this).attr("src","_img/nav/about_off.gif"); 
}); 


$(".artists").hover(function() { 
    $(this).attr("src","_img/nav/artists_over.gif"); 
     }, function() { 
    $(this).attr("src","_img/nav/artists_on.gif"); 
}); 


$(".help").hover(function() { 
    $(this).attr("src","_img/nav/help_over.gif"); 
     }, function() { 
    $(this).attr("src","_img/nav/help_off.gif"); 
}); 

Mais voudrait évidemment passer le titre de l'image (« à propos de », les artistes », « aide ») pour que je puisse réduire répété code.

Toute aide très appréciée.

Merci

Ronnie

+1

Avez-vous essayé CSS? – Jason

+0

Oui merci, j'ai essayé CSS. – rnnbrwn

Répondre

3
function hover(img) { 
    $("."+img).hover(function() { 
    $(this).attr("src","_img/nav/"+img+"_over.gif"); 
     }, function() { 
    $(this).attr("src","_img/nav/"+img+"_off.gif"); 
    }); 
} 
+0

Besoin de changer '$ (nom_classe)' '$ (". "+ Nom_classe)' – Sean

+0

Bon point. fixé. –

+0

Cela ne fait que changer deux fois l'attribut src ... rendant ainsi la première instruction inutile. Vous devez utiliser une fonction de rappel pour _off.gif. Vois ma réponse. –

0

Je ne suis pas sûr de ce qui se passe avec la seconde fonction dans la fonction de vol stationnaire, mais vous pouvez faire quelque chose comme ceci:

$(".about .artists .help").hover(function(){ 
    $(this).attr('src','_img/nav/' + $(this).attr('class') + '_over.gif') 
}); 

vous pouvez appliquer le même principe à votre marche/arrêt gifs aussi.

+0

utilisé celui-ci, mais je l'ai fixé en changeant $ ("A propos de .artists .help ") à $ (". A propos, .artists, .help") Merci pour votre aide, toutes les personnes. – rnnbrwn

+0

Puis sélectionnez ceci comme votre réponse. – pal4life

1

Vous pouvez quelque chose comme ceci:

function ElementHover(class_name, src_over, src_off) { 
    $("."+class_name+"").hover(function() { 
     $(this).attr("src", src_over); 
     }, function() { 
     $(this).attr("src", src_off); 
    }); 

} 
1
function HoverPic(name){ 
    $("."+name).hover(function() { 
     $(this).attr("src","_img/nav/"+name+"_over.gif"); 
      }, function() { 
     $(this).attr("src","_img/nav/"+name+"_off.gif"); 
    }); 
} 
Questions connexes