无法读取未定义的属性长度(空容器警报消息)

问题描述 投票:0回答:1

如果“匹配”表示为胡须模板,我该如何实现代码,我想在其中返回一条警告消息“无匹配”和“匹配可用”。它在else语句中工作正常,但在if语句中,它什么都不返回。这是代码:

$.each(data.matches, function() {
               var match = this;
                if(this.matches == 0){
                    alert('no matches');
                }
                else{
                    alert('matches available');
                }
                $contents += Mustache.render(container, this);
            });

任何想法怎么样?谢谢!

jquery mustache
1个回答
0
投票

据我了解你data对象和matches这个对象列表里面看起来当没有匹配它返回为undefined而不是空数组[]所以它抛出异常无法读取未定义的属性长度

所以你有没有匹配的返回空数组或检查匹配对象之前迭代列表如下

if(!data.matches){
   alert('no matches');
}
else{
   alert('matches available');
   $.each(data.matches, function() {
          var match = this;
          $contents += Mustache.render(container, this);
   });
}
© www.soinside.com 2019 - 2024. All rights reserved.