【问题标题】:Append additional value to a variable for each ID in jQuery将附加值附加到 jQuery 中每个 ID 的变量
【发布时间】:2014-02-25 19:19:11
【问题描述】:

我有这两个随机拾取图片的轮播。 [fiddle] 他们每个人 (#carousel1,#carousel2) 从各自不同的内部数组中获取图片和链接。

我的问题是轮播将有自己的图像路径和指向不同子域的链接,但脚本使用addImage("/pic/" + images[i][0], "/url/" + images[i][1]);} 中的实际路径(“url”和“pic”)。我能想出的唯一解决方案是使用域作为变量

var domain = "www.picture.com";

在实际路径“/pic/”和“/url/”的位置,然后根据轮播ID附加实际图像路径和链接到domain。我不确定如何做第二部分,以及这是否是正确的方法。谁能给我一些解决方案?

function randomizeCarousel(selector, images) {
  var i, l, carousel = $(selector);

  function shuffle(images) {
    var i, shuffled = [];
    while(images.length) {
      i = Math.floor(Math.random() * images.length);
      shuffled = shuffled.concat(images.splice(i, 1));
    }
    return shuffled;
  }

  function addImage(src, href) {
    var container = $("<div>"),
        link      = $("<a></a>").attr("href", href).appendTo(container),
        img       = $("<img/>").attr("src", src).appendTo(link);
    carousel.append(container);
  }

  images = shuffle(images.slice(0));
  for(i = 0, l = images.length; i < l; i++) {
    addImage("/pic/" + images[i][0], "/url/" + images[i][1]);
  }

  carousel.jsCarousel({
    onthumbnailclick: function(src) { load(src); },
    autoscroll:       true,
    circular:         true,
    masked:           false,
    itemstodisplay:   3,
    orientation: 'h'
  });
}

$(function () {
  randomizeCarousel("#carousel1", [...]); // add your 1st array here
  randomizeCarousel("#carousel2", [...]); // add your 2nd array here
  // ... etc.
});

【问题讨论】:

  • 我想我并没有真正在您的代码中看到问题。为什么不只创建 2 个域变量和(如果域内的路径不同)、2 个路径变量,并酌情使用它们?

标签: javascript jquery variables random append


【解决方案1】:

这样的?

var domain1,domain2,path1,path2;
  domain1 = 'http://domain.tld';
  domain2 = 'http://domain2.tld';
  path1 = domain1+"/pic/";
  path2 = domain2+"/url/";
    addImage(path1 + images[i][0], path2 + images[i][1]);

【讨论】:

  • 有没有办法只为#carousel1 分配path1,只为#carousel2 分配path2?据我了解,您的建议只会将所有路径混合在轮播中。
  • 我不知道你的插件是如何设置的,但你应该能够将它作为可选参数传递或在插件本身中设置一些东西来处理它。
猜你喜欢
  • 1970-01-01
  • 2016-10-11
  • 2016-07-14
  • 2017-01-10
  • 2019-11-23
  • 2022-08-19
  • 2014-03-15
  • 2023-03-25
  • 2014-07-25
相关资源
最近更新 更多