开发者

Custom jQuery Functions and Arguments

I have written this scirpt:

 $(document).ready(function () {
   $('#tb1 li').hover(function () {
    var head = $(this).attr("title");
    var image = $(this).find("a").attr("rel");
    $('.aCnt img').attr("src", image);
    $('.aCnt span').html(head);

   });
    $('#tb1 li').eq(0).hover();
}); 

I want to make this script global

function interActive(myID, myClass){
    ID = '#' + myID;
    cls = '.' + myClass;
     $('ID li').hover(function () {
    var head = $(this).attr("title");
    var image = $(this).find("a").attr("rel");
    $('cls img').attr("src", image);
    $('cls span').html(head);

   });
    $('ID li').eq(0).hover();
}

I know that jQuery function not similar to for example php functions. The interActive functions will not开发者_开发知识库 work in jQuery. How can I modify this function for jQuery? Thanks in advance.


The variables ID and cls are being treated literally as strings when put them inside quotes. You need to concatenate them like this: cls + ' img'.

function interActive(myID, myClass){
    var ID = '#' + myID;
    var cls = '.' + myClass;
    $(ID + ' li').hover(function () {
        var head = $(this).attr("title");
        var image = $(this).find("a").attr("rel");
        $(cls + ' img').attr("src", image);
        $(cls + ' span').html(head);

    });
    $(ID + 'li').eq(0).hover();
}

You may also consider writing a jQuery plugin for this, such as:

$.fn.interActive = function (target) {
    this.find('li').hover(function () {
        var head = $(this).attr('title');
        var image = $(this).find('a').attr('rel');
        $(target).find('img').attr('src', image);
        $(target).find('span').html(head);
    }).eq(0).hover();
};

Which can be used like this:

$("#someID").interActive(".someClass");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜