【问题标题】:Using Jquery .addClass on html elements in array在数组中的 html 元素上使用 Jquery .addClass
【发布时间】:2012-03-30 06:01:00
【问题描述】:

我有一些填充数组的 html 图像标签。在页面上 - http://www.digitalbrent.com/lab - 显示了数组中的三个元素。单击按钮后,我需要向它们添加一个类。如果从数组中显示 imgs,则每个类都不同。代码如下:

$(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上查看了类似的问题,但没有运气。我已经研究这个项目一段时间了,找不到任何东西。

【问题讨论】:

  • 对不起,如果您正在查看页面,可能需要按增加按钮才能看到数组

标签: jquery arrays element


【解决方案1】:

您的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 相关的区别吗?让我知道我是否可以更清楚地说明。
【解决方案2】:

您应该使用each() 来迭代jQuery 集合,而不是$.each()

shipImgs.each(function () {
    var img = "<img src='" + $(this).attr('src') + "' alt='space'/>";
    imgArr.push(img);
});

【讨论】:

    【解决方案3】:

    您正在尝试将.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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      • 2016-03-23
      相关资源
      最近更新 更多