【问题标题】:Jquery .index() not working though WAMPJquery .index() 无法通过 WAMP 工作
【发布时间】:2013-09-19 17:40:24
【问题描述】:

我对 .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 上的 localhost/ 运行良好,但一旦我尝试使用我的 ip 521.xxx.xxx/ 共享它,这就是索引计数停止正常工作的时候。

【问题讨论】:

  • WAMP 不能影响 javascript 的执行方式,javascript 是客户端。

标签: javascript jquery wamp mamp


【解决方案1】:

看看index() 做了什么。 documentation says

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

你不想要索引!您想知道子元素的数量。为此,您想使用.length

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

【讨论】:

  • 本地运行时为什么返回6?
  • 我不知道,也许你有不同的缓存 jQuery 版本?我所知道的是,如果你想要孩子的数量,它应该是长度。 index() 是完全不同的东西。
【解决方案2】:

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

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

【讨论】:

  • 感谢您的帮助。似乎工作正常。我仍然很困惑为什么我以前从未遇到过这个问题以及为什么它在本地工作。
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 2019-01-24
    • 1970-01-01
    • 2015-08-04
    • 2012-10-16
    • 1970-01-01
    • 2012-01-08
    • 2014-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多