Add jQuery function to specific elements

前端 未结 9 1478
悲&欢浪女
悲&欢浪女 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:15

    If you're wanting this function only for particular selectors, the following will work for you. I've just had a scenario where I've needed this and it works nicely.

    $('.my-selector').each(function(){
    
        $(this).init.prototype.getUrl = function(){
            // do things
        };
    })
    

    then later on you can do

    $('.my-selector').getUrl()
    

    without having to define it as a plugin, or use data or bind/on/trigger events.

    Obviously you can change the function to return the containing object if you want to use it in chaining by returning this

    $('.my-selector').each(function(){
    
        $(this).init.prototype.getUrl = function(){
            // do things
            return this;
        };
    })
    

提交回复
热议问题