尝试在 jQuery 脚本中使用不同的数组数据结构



我遇到了这个随机图像旋转器

var theImages = new Array() 
    theImages[0] = 'img1"'  theImages[1] = 'img2"'......   
var shuffled = [];    
while (theImages.length) {
    shuffled.push(theImages.splice(Math.random() * theImages.length, 1));
}            
$(document).ready(function(){        
    //Runs Script each time there is an <li>
    $("#news li").each(function(index){                
        //Puts Image in front of everything in <li>
        $(this).prepend('<img src="'+shuffled[index]+'">');            
    });
});

我把它集成到一个jQuery轮播中。你可以在这里看到(我的小提琴)。 问题是我想用于旋转木马的数组结构与旋转器的数组结构不同。旋转器使用

var theImages = new Array() 
theImages[0] = 'img1"'
theImages[1] = 'img2"'
theImages[2] = 'img3"'

但是我想将以下内容用于轮播,因为我也想输入每张图片的链接。

var theImages = [
['img1','url_1'],
['img2','url_2'],
['img3','url_3']];

我正在寻找的结果是这样的:

<div id="carousel1"> 
<div class="1"><a href="url_1"><img src="img1"></a></div>
<div class="1"><a href="url_2"><img src="img2"></a></div>......

从我所读到的内容来看,我必须使用for in loop来分配数据,而不能简单地使用图像旋转器正在使用的内容:

$("#carousel1 .1").each(function(index){    
$(this).prepend('<a href="'+imgPath+''+shuffled[index]+'"><img 
src="'+urlPath+''+shuffled[?url](?url)+'"></a>');

这是真的吗?有什么方法可以让我填充轮播中的图像和网址?

不,永远不要将for ... in用于数组。你所要做的就是改变

'<img src="'+shuffled[index]+'">'

'<a href="'+imgPath+shuffled[index][1]+'"><img src="'+urlPath+shuffled[index][0]+'"></a>'

因为图像路径是内部数组的第一个元素,而链接是第二个元素。

有关详细信息,请参阅访问/处理(嵌套)对象、数组或 JSON。

(我假设imgPathurlPath实际上是在某处定义的,并且包含URL。如果没有,则应删除它们。

您的问题是您的源数组(随机值)只包含一个值,但最终的结果是您希望具有值对的值。额外的数据需要来自某个地方,计算机不能只是发明它。

最简单的方法是修改随机代码,而不是随机播放单个字符串

,而是对字符串进行随机播放。

即类似

var theImages = new Array() 
theImages[0] = ['img1"', data1]
theImages[1] = ['img2"', data2]

for(var i=0;i<theImages.length;i++){
    newTheImagesArray.push([theImages[i],theImages[i]])
}

这应该适用于您想要的

最新更新