Add jQuery function to specific elements

前端 未结 9 1462
悲&欢浪女
悲&欢浪女 2020-12-07 18:56

I know that you can add new jQuery functions by $.fn.someFunction = function()

However, I want to add functions to specific elements only. I tried this

9条回答
  •  醉梦人生
    2020-12-07 19:13

    @Reigel's answer is great! However you could also use the $.fn syntax and let your function only handle certain elements:

    $.fn.someFunction = function(){
        this.each(function(){
            // only handle "someElement"
            if (false == $(this).hasClass("someElement")) {
                return; // do nothing
            }
    
            $(this).append(" some element has been modified");
    
            return $(this); // support chaining
        });    
    };
    
    // now you can call your function like this
    $('.someElement').someFunction();            
    

    See working jsfiddle: http://jsfiddle.net/AKnKj/3/

提交回复
热议问题