【问题标题】:generalized .length check on functions函数的广义 .length 检查
【发布时间】:2010-02-15 23:24:46
【问题描述】:

当我在 JS 或 jQuery 中编写函数并且需要参数时,我使用 if something.length 技巧...

this.example = function(e) {
  if ($(e).length) {
    /*blablabla*/
  } else {
    return false;
  }
}

但我不想在所有功能中都这样做。有没有办法概括这一点?

喜欢:

this.ck = function(e) {
  return function(e){
    if (!(e.length)) { return false;}
  }
}

this.example = function(e) {
     ck(e)
    /*blablabla*/

}

【问题讨论】:

    标签: jquery


    【解决方案1】:

    也许是这样,但见下文:

    function ifNonEmpty(f) {
      return function(e) {
        if (!$(e).length) return false;
        return f(e);
      };
    }
    

    你会这样使用它:

    var myCoolFunction = ifNonEmpty(function myCoolFunction(e) {
      // your implementation
    };
    

    然而,我建议不要编写将 jQuery 对象作为参数的函数,而是将这些函数编写为您自己的 jQuery 插件。

    【讨论】:

      【解决方案2】:

      我会建议以下内容。

      这个例子将首先测试参数是否真的包含任何东西(即不为空),然后你的 .length 检查可能是它是否

      function isNonEmpty(p){
          if ( (p != null) && (p.length > 0) ){
              //test
          }
      }
      

      无论如何,我会警惕使用 .length。例如,如果你传递一个字符串.length就会有一个值!

      测试某物是否为 jQuery 对象:

      alert(p instanceof jQuery); //will alert "true" if p is a jQuery object.
      

      所以,这给了我们:

      function isNonEmpty(p){
          if ( (p != null) && (p instanceof jQuery) && (p.length > 0) ){
              //test
          }
      }
      

      或类似的东西。不管怎样,那里应该有足够的代码来定制你的意图。

      【讨论】:

        猜你喜欢
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        • 2017-11-28
        • 2023-01-31
        • 2014-05-21
        • 1970-01-01
        相关资源
        最近更新 更多