简体   繁体   中英

write a function to get all elements with data attribute

I'm trying to build my own jQuery function for personal use later, but I'm new in building like these plugins so I started to learn then apply what i want to do, but I faced problems .. what I'm trying to build is a jQuery function gets all elements (for now inputs ) with attribute data-x , then apply another jQuery method on it, for example addClass('class') so instead of this complix line of code $('input[data-x="test"]').addClass('class'); I want to use my function getElems('x','test').addClass('class');

this is what I wrote ( fiddle )

(function ($){
$.fn.getElems = function( key, value ) {
        var elems = [];
        for (var x = 0; x < this.length; x++) {
            if($(this[x]).data(key) === value) {
                elems.push(this[x]);
            }
        }
        return elems;
    };
}(jQuery));

when I try to addClass i got error.. undefined is not a function .

That's probably because you are calling jQuery methods on an array. You could use the filter method, and return the filtered collection:

$.fn.getElems = function (key, value) {
    return this.filter(function () {
        return $(this).data(key) === value;
    });
}

Your plugin should return this reference if you want to be able to chain jQuery methods:

(function ($) {
    $.fn.getElems = function (key, value) {
        return this.filter(function() {
            return $(this).data(key) === value;
        });
    };
}(jQuery));

In general you should probably make use of jQuery filter method for this purpose. This way your code will be more jQuery-like.

Demo: http://jsfiddle.net/pg87ns53/3/

Or if you still want to stick with your version with for loop, then you will have to return something like return $(elems); instead just elems :

$.fn.getElems = function (key, value) {
    var elems = [];
    for (var x = 0; x < this.length; x++) {
        if ($(this[x]).data(key) === value) {
            elems.push(this[x]);
        }
    }
    return $(elems);
};

however this looks a little clumsy.

Demo: http://jsfiddle.net/pg87ns53/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM