[英]More efficient way to write jQuery function
有沒有更好的方法來編寫此函數? 我敢肯定我在這里只需要一個函數,但是我不知道怎么寫!
(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);
這可能要簡單得多:
jQuery.fn.codeexists = function(code) {
return jQuery('#fault-list-tbl tbody tr .fault-tbl-code').filter(function() {
return this.html() === code;
}).length > 0;
};
filter
將元素過濾為只有html
code
元素,而length
是多少個元素。 因此,如果有0個以上( length > 0
)的元素以html
為code
,則返回true。
您也可以這樣寫:
(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.