所以我可以将我想要的所有图像放入一个数组并将它们传递给 $image。但是,当我尝试遍历该数组时,它只会不断提醒同一个项目 3 次。
我遇到问题的代码。
getItem : function($image){
console.log($image)
console.log(jQuery.type($image))
var setup ='<img src="' + $($image).attr('href') + '" title="' + $($image).attr('title') + '"/>';
$.each($image, function(i){
alert( setup);
});
}
HTML
<a href="images/slideshow/1-GW.PhillipBarnhart.ReverendMemory.jpg" title="Phillip Barnhart as:
Reverend Memory - a clergyman who stands for decorum and truth." rel="slideshow"><img src="images/view-slideshow.jpg" width="490" height="352" alt="View Slideshow"></a>
<a rel="slideshow" href="images/slideshow/2-GW.BethBrooks.POLLYTODD.jpg">fff</a>
<a rel="slideshow" href="images/slideshow/3-GW.NickHale.NOSTALGIA.jpg">test</a>
整个脚本或者如果你喜欢 jsFiddle,这里是一个链接。 http://jsfiddle.net/h3az4/
var slideShow = {
config : {
wrapper : 'body',
container : 'div',
anchor : 'a[rel="slideshow"]'
},
init : function(config) {
$.extend(slideShow.config, config);
$(slideShow.config.anchor).hide();
$(slideShow.config.wrapper).find(slideShow.config.anchor)
.eq(0)
.show()
.click(function(e){
e.preventDefault();
slideShow.getItem($(slideShow.config.anchor));
});
},
getItem : function($image){
console.log($image)
console.log(jQuery.type($image))
var setup ='<img src="' + $($image).attr('href') + '" title="' + $($image).attr('title') + '"/>';
$.each($image, function(i){
alert( setup);
});
},
createTumbnail : function($image){
}
};
$(document).ready(function() {
slideShow.init();
});
最佳答案
你使用 $.each 循环是错误的。
您的第一个问题是如果 $image 是一个列表,$image.attr("x") 将获取列表中第一个元素的属性。你想要的是 $($image[i]) 或使用 .get
第二个问题是在循环外声明 var setup
。这意味着它声明并使用了一次而不是 3 次(因为你有 3 个项目)。
$.each($image, function(i){
var setup ='<img src="' + $(this).attr('href') + '" title="' +
$(this).attr('title') + '"/>';
alert( setup);
});
当您使用 $.each
时,函数中的 this
对象将依次引用数组中的每个对象。在本例中,this
是一个 DOM 对象,因此您要使用 $(this)
来获取 jQuery 图像对象。
在此处查看工作示例 http://jsfiddle.net/Raynos/h3az4/3/
关于javascript - 不会在 jQuery 中遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4798520/