如何将其变成可链接的 jquery 函数?
我的函数返回基于数据属性的过滤(数组)项目列表。
如果我能让这个函数可链接,我会很高兴:
$(document).ready(function (){
function filterSvcType (svcType) {
var selectedServices = $("#service-list div");
var chose = selectedServices.filter(function() {
return $(this).data("service-type") == svcType;
});
console.log(chose);
}
filterSvcType("hosting");
});
我想做的是这样调用它:
filterSvcType("hosting").fadeOut();
我该怎么做?
My function returns a filtered (array) list of items based on the data attribute.
I would like it if I could make this function chainable:
$(document).ready(function (){
function filterSvcType (svcType) {
var selectedServices = $("#service-list div");
var chose = selectedServices.filter(function() {
return $(this).data("service-type") == svcType;
});
console.log(chose);
}
filterSvcType("hosting");
});
What I want to do is call it like this:
filterSvcType("hosting").fadeOut();
How do I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要添加的只是在
console.log
调用之后return selected;
。但你也可以把它变成一个 jQuery 插件
然后你可以调用它,
它是一个更 jQueryish 的。
All you need to add is
return chose;
after yourconsole.log
call.But you could also turn this into a jQuery plugin
Then you can call as
Which is a bit more jQueryish.
您可以只返回过滤后的元素。
这与所有 jQuery 方法所使用的原理相同。他们对您发送的任何选择器和/或集合执行一些逻辑,然后返回该集合。所以现在你可以这样做:
这实际上与链接相同。
这里有一个快速测试来展示它的实际效果
You can just return your filtered elements
This is the same principle that's being used on all jQuery methods. They do some logic to whatever selector and/or collection you send in, and then return that collection back. So now you could do:
Which is the same as chaining, really.
Here's a quick test to show it in action