在数组中使用jQuery的.addClass方法添加HTML元素的类名

3

我有一些HTML图像标签填充了一个数组。在页面上 - http://www.digitalbrent.com/lab - 数组中的三个元素被显示。我需要在按钮点击后为它们添加一个类。每个显示在数组中的图片的类别都不同。这是代码:

$(document).ready(function(){        //populates array with images

    var shipImgs = $("#thumb_slider").children();
    console.log(shipImgs);

    $.each(shipImgs,function(i,elem){
        var tag = "<img src='" + $(elem).attr('src') + "' alt='space'/>"; // This is how I made the image tags.
        imgArr.push(tag);
    });
    console.log(imgArr);

});

$("#basic_ul").html(imgArr[b] + imgArr[a] + imgArr[c]); //displays the images
        imgArr[b].addClass("left_slot");
        imgArr[a].addClass("middle_slot");
        imgArr[c].addClass("right_slot");

我也尝试过在数组项周围使用选择器$(imgArr[b]).addClass("left_slot"),但那也不起作用。非常感谢任何建议。我在stackoverflow上查看了类似的问题,但没有运气。我已经研究了这个项目一段时间,但找不到任何东西。

抱歉,如果您正在查看页面,则可能需要按增加按钮才能查看数组。 - Digital Brent
3个回答

4

你的imgArr只包含一组字符串,这些字符串是图像标签HTML。

相反,如果将该字符串传递给jQuery函数,则会获得一个内存节点,您可以将其添加到文档中。

尝试将上面的代码更改为:

$(document).ready(function(){        //populates array with images
    var $basicUl = $('#basic_ul'); // cache the selector
    var shipImgs = $("#thumb_slider").children().each(function(index, element) {
        var newImg = $("<img />").attr({src: this.src, alt: 'space'}).addClass(index == 0 ? "middle_slot" : (index == 1 ? "left_slot" : "right_slot"));
        $basicUl.append(newImg);
    });
});

@DigitalBrent 没问题!我的代码有哪些方面不清楚吗?你是否理解 HTML 字符串和实际 DOM 元素之间的重要区别,特别是与 jQuery 相关的区别?如果需要我澄清任何事情,请告诉我。 - GregL

1
你应该使用each()来迭代jQuery集合,而不是$.each()
shipImgs.each(function () {
    var img = "<img src='" + $(this).attr('src') + "' alt='space'/>";
    imgArr.push(img);
});

1
你正在尝试对一个字符串进行 .addClass 操作 - imgArr[b] 是一个字符串而不是元素,你不能向一个字符串中添加类。可以尝试这样写:
$(document).ready(function(){        //populates array with images

    var shipImgs = $("#thumb_slider").children();
    console.log(shipImgs);

    $.each(shipImgs,function(i,elem){
        var tag = $("<img src='" + $(elem).attr('src') + "' alt='space'/>"); // This is how I made the image tags.
        imgArr.push(tag);
    });
    console.log(imgArr);

});

$("#basic_ul").append(imgArr[b]);
$("#basic_ul").append(imgArr[a]);
$("#basic_ul").append(imgArr[c]);
imgArr[b].addClass("left_slot");
imgArr[a].addClass("middle_slot");
imgArr[c].addClass("right_slot");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接