你好 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)
});
});