jQuery 类型错误:$(...).parents(...).size 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40002951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:14:15  来源:igfitidea点击:

TypeError: $(...).parents(...).size is not a function

jquerytypeerror

提问by Qrzysio

I have a basic script which allows me to click on the website's background, excluding #content.

我有一个基本的脚本,它允许我点击网站的背景,不包括#content.

After upgrading jQuery to 3.1.0 version, I get this error: TypeError: $(...).parents(...).size is not a function.

将 jQuery 升级到 3.1.0 版本后,出现此错误: TypeError: $(...).parents(...).size is not a function.

<script type="text/javascript">
  $(function() {
    $("#background").click(function(e) {
      if (e.target.id == "wrapper" || $(e.target).parents("#wrapper").size()) 
      {
        // do nothing
      } 
      else
      {
        window.open('http://example.com');
      }
    });
  })
</script>`

I don't know how to fix it. jQuery is loaded properly. Please help.

我不知道如何修复它。jQuery 已正确加载。请帮忙。

回答by charlietfl

size()was deprecated years ago and removed in version 3 ... use lengthinstead

size()多年前已弃用并在版本 3 中删除...length改为使用

if (e.target.id == "wrapper" || $(e.target).parents("#wrapper").length)

All you had to do was look this up in the size() docsto find this out

您所要做的就是在size() docs中查找此内容以找到答案

回答by Shubh

Please use 'length'like @charlietflsuggested. But I was unable to trace from where the error was getting displayed, hence I ended up with below.

请像@charlietfl建议那样使用“长度”。但是我无法从显示错误的位置进行追踪,因此我最终得到了下面的结果。

(function ($) {
    $.fn.extend({
        size: function () {
            return $(this).length;
        }
    });
})(jQuery);