0

你好 Stack Overflowians,

我似乎错误地将 .length 与子选择器 (>) 结合使用。完整的脚本如下,但这是有问题的行:

$(id > '.fade-cycle-element').length;

如果我只是通过 .class 选择,jQuery 返回页面上所有$('.fade-cycle-element').length匹配元素的计数,而不是特定父 #id 的匹配子元素的数量。如果我使用上面的选择器方法,jQuery 返回 0。

我究竟做错了什么?非常感谢您的帮助。

最亲切的问候,

./ndm

/* This script takes a set of elements (e.g., images) and rotates them according to a 

specified rate.
 * 
 * Example HTML:
 * <div class="fade-cycle-element-wrapper" data-rate="4000">
 *   <img class="fade-cycle-element" src="01.jpg" />
 *   <img class="fade-cycle-element" src="02.jpg" />
 *   <img class="fade-cycle-element" src="03.jpg" />
 * </div>
 *
 * The idea for this script is based on Brian McNitt's rotating image script:
 * 
 *   http://trendmedia.com/news/infinite-rotating-images-using-jquery-javascript
 *   
 *   Copyright (c) 2010 TrendMedia Technologies, Inc., Brian McNitt. 
 *   All rights reserved.
 *    
 *   Released under the GPL license
 *   http://www.opensource.org/licenses/gpl-license.php
 *   
 *   **********************************************************************
 *   This program is distributed in the hope that it will be useful, but
 *   WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 *   **********************************************************************
 * 
 */

function elementRotate(elemID) {

  //get cycle rate and set derivatives
  var id = '#' + elemID;
  var cycle = $(id).data('rate');
  var start = (cycle*.25);
  var fade = (cycle*.25);

  //queue up the elements and start the cycle
  var elements = $(id > '.fade-cycle-element').length;
  var current = 0;
  $(id > '.fade-cycle-element').eq(current).fadeIn(start);

  //cycle through elements    
  var engine = setInterval(function(){
    $(id > '.fade-cycle-element').eq(current).fadeOut(fade);
    if (current == (elements - 1)) {
      current = 0;
    } else {
      current++;
    }
    $(id > '.fade-cycle-element').eq(current).fadeIn(fade);
  }, cycle);

};

$(window).load(function() {

  var elemSetCount = 1;
  $('.fade-cycle-element-wrapper').each(function() {
    $(this).attr("id", "elemSet" + elemSetCount++);
    var elemSetID = $(this).attr('id');
    elementRotate(elemSetID)
  });

});
4

1 回答 1

5

您在这里进行比较,而不是编写选择器!您正在比较id字符串'.fade-cycle-element'并将布尔结果传递给 jQuery 函数。

你应该这样做:

$(id + ' > .fade-cycle-element').length;
于 2013-04-03T13:45:43.750 回答