【问题标题】:Jquery each interation problemjquery每次迭代问题
【发布时间】:2011-11-13 19:37:05
【问题描述】:

我得到了这个随机位置脚本。但它只适用于第一张图片......我做错了什么?

var randnumsX = [1,2,3,4,5,6,7,8];
var randnumsY = [1,2,3,4,5,6];

$('#obra img').each(function(i,el) {

    m = Math.floor(Math.random()*randnumsX.length);
    randnumsX = randnumsX.splice(m,1);
    posx = Math.floor(m * 50);

    n = Math.floor(Math.random()*randnumsY.length);
    randnumsY = randnumsY.splice(n,1);
    posy = Math.floor(n * 50);

    $(el).css({position:'absolute', left: posx + 155, top: posy});      
    $(el).fadeIn('slow');

}); 

【问题讨论】:

  • 你的标记是什么样的? id="div" 的单个 div 中的所有图像吗?
  • 如果您调试...它甚至会循环吗?我的意思是,$('div img') 检索到的集合有多少张图片?
  • 修复了代码,但仍然无法正常工作。标记是正确的。我有一个 div (#obra),里面有 5 张图片。我想随机化位置而不重复上一个。

标签: jquery iteration each


【解决方案1】:

splice 返回移除的元素,而不是移除元素的数组。

【讨论】:

  • randnumsX.splice(m,1); 替换randnumsX = randnumsX.splice(m,1); 就可以了。另请注意,名称相似的 slice() 方法不会像 splice() 那样修改数组——注意拼写错误。
  • x = randnumsX.splice(m,1); posx = Math.floor(x*50);
【解决方案2】:

如果您正在访问 div,那么您将不需要 # 符号

$('div img').each(function(i,el) {

m = Math.floor(Math.random()*randnumsX.length);
randnumsX = randnumsX.splice(m,1);
posx = Math.floor(m * 50);

n = Math.floor(Math.random()*randnumsY.length);
randnumsY = randnumsY.splice(n,1);
posy = Math.floor(n * 50);

$(el).css({position:'absolute', left: posx + 155, top: posy});      
$(el).fadeIn('slow');

});

【讨论】:

  • 嗨 Meenakshi,已修复原帖。
猜你喜欢
  • 1970-01-01
  • 2012-10-08
  • 2011-04-07
  • 2013-12-18
  • 1970-01-01
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
  • 2013-05-07
相关资源
最近更新 更多