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

twi*_*ter 6 javascript jquery

我有一个函数接受它作为参数操作所需的元素 element

function changeColor(element){
   $(element).find('.middleBox').each(function(){
       $(this).//do some stuff that does not matter now;
   });
}
Run Code Online (Sandbox Code Playgroud)

我这样称呼它

changeColor($(document)); //this applies it to the whole document
changeColor($('#sectionOne')); //this applies it to only part of the document 
Run Code Online (Sandbox Code Playgroud)

我想将它从接受其对象作为参数的格式更改为此格式.我该怎么做

$('#sectionOne').changeColor();
$(document).changeColor();
Run Code Online (Sandbox Code Playgroud)

Mar*_*ich 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);
Run Code Online (Sandbox Code Playgroud)