如何将函数从函数(元素)语法转换为$(element).function()语法

时间:2011-02-26 01:40:40

标签: javascript jquery

我有一个函数接受它作为参数element

进行操作所需的元素
function changeColor(element){
   $(element).find('.middleBox').each(function(){
       $(this).//do some stuff that does not matter now;
   });
}

我这么称呼它

changeColor($(document)); //this applies it to the whole document
changeColor($('#sectionOne')); //this applies it to only part of the document 

我想将它从接受其对象的格式更改为此格式的param。我该怎么做

$('#sectionOne').changeColor();
$(document).changeColor();

2 个答案:

答案 0 :(得分:6)

正如Nikita所说,你需要编写一个jQuery插件。这是一个基本的例子,应该足以满足你的目的:

(function($) {
    $.fn.changeColor = function() {
        return this.each(function() {

            $(this).find('.middleBox').each(function() {
                $(this).//do some stuff that does not matter now;
            });

        });
    };
})(jQuery);

答案 1 :(得分:1)

您想要创建一个jQuery插件。 jQuery人员为此提供了a tutorial

如果你不喜欢阅读,你几乎可以复制粘贴maxHeight example并替换里面的逻辑。