有没有更好的方法来编写这个函数?我很确定我在这里只需要一个函数,但我不知道如何编写它!
(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
) 个元素将 code
作为它们的 html
,它返回 true。
关于javascript - 编写 jQuery 函数的更有效方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19897695/