通过Jquery声明变量并在其他地方使用它们
救命啊!我试图在div(.SlideContent)中获取声明为内联的背景图像,并将该值放入相邻的OL LI中,如下所示:通过Jquery声明变量并在其他地方使用它们,jquery,Jquery,救命啊!我试图在div(.SlideContent)中获取声明为内联的背景图像,并将该值放入相邻的OL LI中,如下所示: $( document ).ready(function() { $(".banner ul li").each(function() { $(this).children('a').each(function() { $(this).children('.SlideContent').each(function() {
$( document ).ready(function() {
$(".banner ul li").each(function() {
$(this).children('a').each(function() {
$(this).children('.SlideContent').each(function() {
var backgroundImage = $(this).css("background-image");
});
});
});
$(".banner ol.dots").each(function() {
$(this).children('li.dot').each(function() {
$(this).css("background-image", backgroundImage);
});
});
});
当我尝试此操作时,它只是一遍又一遍地用相同的图像填充OL列表项。它超出了范围-Javascript具有函数范围,而不是块范围。除非创建闭包,否则变量的寿命与函数的寿命相同
$( document ).ready(function() {
var backgroundImage = '';
$(".banner ul li").each(function() {
$(this).children('a').each(function() {
$(this).children('.SlideContent').each(function() {
backgroundImage = $(this).css("background-image");
});
});
});
$(".banner ol.dots").each(function() {
$(this).children('li.dot').each(function() {
$(this).css("background-image", backgroundImage);
});
});
});
如果您有需要在每个迭代周期中使用的图像数组,请尝试以下操作
var backgroundImage = new Array();
var myIdx = 0;
$( document ).ready(function() {
$(".banner ul li").each(function() {
$(this).children('a').each(function() {
$(this).children('.SlideContent').each(function() {
backgroundImage[myIdx] = $(this).css("background-image");
myIdx++;
});
});
});
myIdx = 0;
$(".banner ol.dots").each(function() {
$(this).children('li.dot').each(function() {
$(this).css("background-image", backgroundImage[myIdx]);
myIdx++;
});
});
});
如果看不到你的HTML,很难理解你想要什么,但是我几乎可以保证你已经过度使用了.each()。
var backgroundImage = new Array();
var myIdx = 0;
$( document ).ready(function() {
$(".banner ul li").each(function() {
$(this).children('a').each(function() {
$(this).children('.SlideContent').each(function() {
backgroundImage[myIdx] = $(this).css("background-image");
myIdx++;
});
});
});
myIdx = 0;
$(".banner ol.dots").each(function() {
$(this).children('li.dot').each(function() {
$(this).css("background-image", backgroundImage[myIdx]);
myIdx++;
});
});
});