Hello Stack Overflowians,
我似乎错误地将.length与子选择器(>)结合使用。完整的脚本如下,但这是有问题的一行:
$(id > '.fade-cycle-element').length;
如果我只是通过.class $('.fade-cycle-element').length
选择,jQuery将返回页面上所有匹配元素的计数,而不是特定父级#id的匹配子级数。如果我使用上面的选择器方法,jQuery返回0。
我做错了什么?非常感谢您的帮助。
Kindest Regards,
./ 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)
});
});
答案 0 :(得分:5)
你在这里进行比较,而不是编写选择器!您正在比较id
和字符串'.fade-cycle-element'
并将布尔结果传递给jQuery函数。
你应该这样做:
$(id + ' > .fade-cycle-element').length;