Javascript颜色小偷在jquery嵌套循环

javascript color thief in jquery nested loop

本文关键字:jquery 嵌套循环 小偷 颜色 Javascript      更新时间:2023-09-26

我有一些动态生成的内容,我需要使用color thief来找到主色。下面是最终的动态输出:

<div class="image_product">
    <img style="display:none;" src="image1.jpg">
    <img style="display:none;" src="image2.jpg">
</div>
<div class="image_product">
    <img style="display:none;" src="image3.jpg">
    <img style="display:none;" src="image4.jpg">
</div>

这是我正在尝试的脚本:

var colorThief = new ColorThief();
$('div.image_product').each(function() {
    $(this).find('img').each(function() {
        var color = colorThief.getColor(this[0]);
        console.log(color);
    });
});

我已经设法让它在其他领域工作,我知道只有一个图像,与以下代码:

var colorThief = new ColorThief();
$('div.basket_item_image').each(function() {
    if($(this).children("img").length > 0)
    {
        var img = $(this).find('img');
        var color = colorThief.getColor(img[0]);
        console.log(color);
    }
});

我知道你必须添加[0]时使用它与JQuery,使其正确访问DOM,但我看不出我的中间代码是如何不工作。什么好主意吗?

你不需要this[0]。在each(), this当前HTML元素被迭代,而不是一个jQuery对象,根据文档:

更重要的是,回调是在当前DOM元素的上下文中触发的,因此关键字this指的是该元素。

因此,只使用this访问当前元素(当前<img />),而在each()内。

var colorThief = new ColorThief();
$('div.image_product').each(function() {
    $(this).find('img').each(function() {
        var color = colorThief.getColor(this);
        console.log(color);
    });
});