[英]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');
我稍后尝试构建自己的jQuery函数供个人使用,但是我像这些插件一样在构建中是新手,所以我开始学习然后应用我想做的事情,但是我遇到了问题。 build是一个jQuery函数,获取具有data-x
属性的所有元素(现在inputs
),然后在其上应用另一种jQuery方法,例如addClass('class')
因此代替了代码$('input[data-x="test"]').addClass('class');
I want to use my function getElems('x','test').addClass('class');
我想使用我的函数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
. 当我尝试addClass时出现错误.. undefined is not a function
。
That's probably because you are calling jQuery methods on an array. 那可能是因为您要在数组上调用jQuery方法。 You could use the filter
method, and return the filtered collection: 您可以使用filter
方法,并返回过滤后的集合:
$.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: 如果您希望能够链接jQuery方法,则您的插件应返回this
引用:
(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. 通常,您可能应该为此目的使用jQuery过滤器方法。 This way your code will be more jQuery-like. 这样,您的代码将更像jQuery。
Or if you still want to stick with your version with for
loop, then you will have to return something like return $(elems);
或者,如果您仍然希望使用for
循环使用您的版本,那么您将必须返回诸如return $(elems);
instead just elems
: 相反只是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. 但是,这看起来有点笨拙。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.