JQuery, Passing Parameters

杀马特。学长 韩版系。学妹 提交于 2020-01-06 03:09:45

问题


I'm working with some very basic jquery code and would like to condense what I've done into one function with passed parameters.

I have a few of these:

$(".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");
});

But would obviously like to pass the the title of the image ("about", artists", "help") so that I could cut down on repeated code.

Any help much appreciated.

Thanks

Ronnie


回答1:


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



回答2:


You could something like this:

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

}



回答3:


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



回答4:


I'm not sure what's going on with the second function in the hover function, but you can do something like this:

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

you can apply the same principle to your on/off gifs too.



来源:https://stackoverflow.com/questions/1202551/jquery-passing-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!