Jquery .index() 虽然 WAMP 不起作用

Jquery .index() not working though WAMP

本文关键字:WAMP 不起作用 虽然 index Jquery      更新时间:2023-09-26

我在 .index() 上遇到了一个非常奇怪的问题。我一直在当地构建一些东西,一切正常。一旦我将代码放在 WAMP/MAMP 本地托管上,.index() 计数就会停止正常工作。

var prodCont = $(".disaCats");
prodCont.each(function(){
//Checking too see how Many products the category has
var tempIndex = $(this).children(".cardContainer").index();
//If the there are more than 6 products show the dropdownArrow
if(tempIndex > 5){
      $(this).siblings(".disaHeading").children(".showMoreArrow").show();
});//end index calculation

我使用警报返回 tempIndex,它为每个项目返回 0。

我尝试在没有类选择器的情况下使用 .index(this) 和 .children(),但它做同样的事情。我开始认为这是WAMP/MAMP的问题。

任何帮助都非常感谢。

编辑:此脚本通过 WAMP/MAMP 上的本地主机/运行良好,但是一旦我尝试使用我的 ip 521.xxx.xxx/共享它,这就是索引计数停止正常工作的时候。

看看index()是做什么的。文档说:

如果没有参数传递给 .index() 方法,则返回值为 一个整数,指示第一个元素在 jQuery 对象相对于其同级元素。

你不想要索引!您想知道子元素的数量。要做到这一点,您需要使用.length

var tempIndex = $(this).children(".cardContainer").length;

index()替换为 length 以获取集合中的元素数:

//Checking too see how Many products the category has
var tempIndex = $(this).children(".cardContainer").length;

这里似乎是一个逻辑问题,index为您提供集合中元素的索引,但它的集合是子项列表,因此该集合的第一个子项的索引始终是0。 如果您在集合上使用index,则默认行为是对第一个元素执行调用,这就是为什么您总是得到0。 如果你真的只是想孩子总数,那么我建议使用length而不是index