开发者

How to return an array of objects from a method of a jQuery plugin with chainability?

开发者 https://www.devze.com 2023-02-12 22:47 出处:网络
I\'m writing a jQuery plugin called \"myplugin\" with plugin method \"getSomeWhat\". T开发者_StackOverflow中文版his methods may return a collection of somewhat, e.g. attr(\'id\') of element(s) in \".s

I'm writing a jQuery plugin called "myplugin" with plugin method "getSomeWhat". T开发者_StackOverflow中文版his methods may return a collection of somewhat, e.g. attr('id') of element(s) in ".someclass". I'd like to maintain the chainability, but I can't find from the Internet.

Please kindly advise how to achieve.

$(".someclass").myplugin('getSomeWhat').each(function() {
    //some stuff for each somewhat
});

Thanks!

William Choi


You can't return a non jQuery object and retain chainability. Simply because the chainability is dependent on the jQuery object. It's of course entirely possible to return a jQuery object and allow stuff to chain to that, but that would kinda defeat the purpose of the lookup method.

If you're looking to iterate over the returned set you might accomplish it like this:

var data = $(".someclass").myplugin('getSomeWhat');
$.each(data, function(i, v) {
    //i is index, v is value (if using object props, i is the propName
});

This makes you of the jQuery generic iterator. It can seamlessly iterate over array as well as objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号