现在我有一堆存储在数组中的图像。我希望这些图像具有“left_slot”,“middle_slot”和“right_slot”的ID。以下代码用于为它们提供那些类名,但不提供ID:
function popArr() {
$("#thumb_slider").children().each(function (index, element) {
var newImg = $("<img />").attr({
src: this.src,
alt: 'space'
}).addClass(index == 0 ? "left_slot" : (index == 1 ? "middle_slot" : "right_slot"));
imgArr.push(newImg);
});
return imgArr;
}
我的问题是,如何更改此函数以根据其索引而不是类来为它们提供ID?我认为这些类与我在页面上其他地方的其他代码段混淆了。谢谢!
答案 0 :(得分:2)
使用attr而不是addClass:
function popArr() {
$("#thumb_slider").children().each(function (index, element) {
var newImg = $("<img />").attr({
src: this.src,
alt: 'space',
id: index == 0 ? "left_slot" : (index == 1 ? "middle_slot" : "right_slot")
})
imgArr.push(newImg);
});
return imgArr;
}
答案 1 :(得分:0)
检查this。因此,请使用“id”属性而不是addClass函数。
答案 2 :(得分:0)
而不是.addClass()
,请使用.prop( "id", ..... )