[英]More efficient way to write jQuery function
Is there a better way to write this function? 有没有更好的方法来编写此函数? I'm pretty sure I only need one function here but I don't know how to write it!
我敢肯定我在这里只需要一个函数,但是我不知道怎么写!
(function(jQuery){
jQuery.fn.codeexists = function(code) {
var codeexist = false;
jQuery('#fault-list-tbl tbody tr').each(function (i, row) {
var id = jQuery(this).find('.fault-tbl-code').html();
if (id == code) {
codeexist = true;
};
});
if (codeexist) {
return true;
} else {
return false;
};
};
})(jQuery);
This could be much simpler: 这可能要简单得多:
jQuery.fn.codeexists = function(code) {
return jQuery('#fault-list-tbl tbody tr .fault-tbl-code').filter(function() {
return this.html() === code;
}).length > 0;
};
filter
filters the elements down to only the ones which have an html
of code
, and length
is how many elements. filter
将元素过滤为只有html
code
元素,而length
是多少个元素。 Therefore, if there's more than 0 ( length > 0
) elements which have code
as their html
, it returns true. 因此,如果有0个以上(
length > 0
)的元素以html
为code
,则返回true。
You can also write it like this: 您也可以这样写:
(function($){
$.fn.codeexists = function(code) {
var codeexist = false;
$('#fault-list-tbl tbody tr .fault-tbl-code').html(function (i, id) {
if (id == code) {
codeexist = true;
};
});
return codeexist;
};
})(jQuery);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.