【问题标题】:Return a certain index返回某个索引
【发布时间】:2013-08-10 19:05:32
【问题描述】:

我有下面的代码,其中函数 getImageNum 接收一个连接有 url 的数组,所以我将这些 url 拆分为一个符号,以便我可以将它们分开。 我的变量 res = path.split("-") 包含分隔的网址。因此 res[0] 给出了一个如下所示的 url:http://www.host.net/dir/file。 但我的问题是我想获取 res var 中的每个 url,以便我可以在幻灯片放映中使用它。因此,我希望能够使用一个自动保留不同索引的变量,而不是 res[0]。请参阅下面的代码了解这个想法。

function getImageNum(imageArray) { 
var path;
var res;
var index = 0;

for (i in imageArray) {
    path = imageArray[i];
}

res = path.split("-");

$("#ContentPlaceHolder1_ContentPlaceHolder1_imageView").attr("src", res[index++]);
}

代码:

$("#ContentPlaceHolder1_ContentPlaceHolder1_imageView").attr("src", res[index++]);

只返回同一张图片,不遍历整个 res 内容

【问题讨论】:

  • 您希望幻灯片如何工作...例如每两秒更换一次图像
  • 你能做一个小提琴吗?
  • 我已经编写了制作幻灯片的代码,它每 5 秒更改一次图像。我只需要将 url 添加到 src 属性,然后幻灯片将负责显示图像

标签: javascript jquery


【解决方案1】:
for (i in imageArray) {
    path = imageArray[i];
}

此代码将遍历imageArray 中的每个图像,然后每次将path 覆盖为最新图像。如果您想在路径中添加更多文本,而不是在需要连接的每个循环中完全替换它。但是,您似乎只想在 res 变量中存储所有路径的数组,那么为什么还要麻烦字符串呢?

for (i in imageArray) {
    res.push(imageArray[i]);
}

其次,index++ 不会自动遍历所有索引,它只是一个运算符,它在为您提供旧值后递增该值。如果您想要所有图像,则必须手动循环遍历 res 中的每个图像。

【讨论】:

  • 当时你说:res.push(imageArray[i]);你只有一长串连接的网址。所以我需要把它们分开。我拥有的代码如此有效,但也许只有在这种情况下它才有效。问题是如何将它传递给 src 属性,以便将 url 添加到 src 属性
【解决方案2】:

如果我明白你想要什么,因为它不是很清楚,你的循环有问题 正如 Lochemage 之前所说,在 for 循环for 循环 外部 使用一个变量来获取其值inside for 循环,将无法正常工作。

var imageArray = ["http://www.example.com/img1-http://www.example.com/img2-http://www.example.com/img3-http://www.example.com/img4","http://www.example.com/img5-http://www.example.com/img6-http://www.example.com/img7-http://www.example.com/img8-http://www.example.com/img9"];
// this is what I assume is your array
var imageArrayNew = [];

for(i=0; i<imageArray.length; i++) {
    res = imageArray[i].split("-");
    for(j=0; j<res.length; j++) {
        imageArrayNew.push(res[j]);
    }
}

// now imageArrayNew is an array that contains Each of the elements in imageArray and you can do stuff with it

http://jsfiddle.net/flish/U5vvv/ - 外观的小提琴


编辑删除了一个额外的“-”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多