广义。长度检查功能 [英] generalized .length check on functions
本文介绍了广义。长度检查功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我在JS或jQuery中编写函数并且需要参数时,我使用 if something.length
trick ...
When i write a function in JS or jQuery and a parameter is required, i use the if something.length
trick...
this.example = function(e) {
if ($(e).length) {
/*blablabla*/
} else {
return false;
}
}
但我不想在所有功能中执行此操作。有没有办法概括这个?
But i dont want to do this in all functions. Is there a way to generalize this?
喜欢:
this.ck = function(e) {
return function(e){
if (!(e.length)) { return false;}
}
}
this.example = function(e) {
ck(e)
/*blablabla*/
}
推荐答案
也许这个,但见下文:
function ifNonEmpty(f) {
return function(e) {
if (!$(e).length) return false;
return f(e);
};
}
您可以这样使用:
var myCoolFunction = ifNonEmpty(function myCoolFunction(e) {
// your implementation
};
我建议不要编写将jQuery对象作为参数的函数,而是将这些函数编写为您自己的jQuery插件。
I would however suggest that instead of writing functions that take jQuery objects as parameters, you write those functions as your very own jQuery plugins.
这篇关于广义。长度检查功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文