如何 jQuery 选择器,获取图像的 src 并将其设置为另一个元素的背景图像?

How to jQuery selectors, get an image's src and set it as a background-image of another element?

我正在尝试在以下情况下进行这项工作:

我的目标是从下面的 html 结构中获取第一张图像的 src,然后将其 src 值设置为 DOM 中存在的另一个元素的 background-image:

HTML 输出,动态加载。

我已经设置了 Instafeed jQuery 插件,它输出以下 html 结构:图像通过 Instagram API.

我想从下面的第一张图片中获取图片 src...

<div id="instafeed">
<div class="col-xs-4">
 <a href="#" target="_blank" class="thumbnail fa-eye fa">
  <img class="dynamic-image" src="https://scontent.cdninstagram.com/hphotos-xpa1/t51.2885-15/e15/10375586_312675495555582_308260980_n.jpg">
 </a>
</div>

<div class="col-xs-4">
 <a href="#" target="_blank" class="thumbnail fa-eye fa">
  <img class="dynamic-image" src="https://scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/e15/10454019_1429094704028916_1903084125_n.jpg">
 </a>
</div>

<div class="col-xs-4">
 <a href="#" target="_blank" class="thumbnail fa-eye fa">
  <img class="dynamic-image" src="https://scontent.cdninstagram.com/hphotos-xpf1/t51.2885-15/e15/1530818_682625665122870_298851871_n.jpg">
 </a>
</div>
</div>

...并将其作为以下目标元素.bgcover的url:

<div class="masthead bgcover" style="background-image: url('https://distilleryimage11-a.akamaihd.net/fdc05880f98511e2af2c22000a9e510c_7.jpg');"></div>

jQuery

下面的代码有效,但是,它获取了 html 中其中一张图片的 img src 而不是第一张图片...

$( window ).load(function() {
// For each image with the class .dynamic-image on the page
$(".dynamic-image").each(function() {
// Grab the image
var image_source = $(this).attr('src');

// Set the background
$(".bgcover").css("background-image",'url('+image_source+')');

 });
});

通过阅读 jQuery's :eq() Selector 文档,我现在正在尝试学习如何使用选择器,但我对 JS/jQuery 还是个新手,所以我非常感谢任何提示使其以正确的方式工作。

.each()中的jquery函数就像一个循环。它将 运行 循环遍历每场比赛。因此,在您上面的代码中,理想情况下它将选择最后一个 img 标签并将其图像设置为背景。

相反,如果您使用 .first() 函数,它将 return 它匹配的第一个元素。这是适合您的实现。

$(window).load(function () {
    // For each image with the class .dynamic-image on the page

    // Grab the image
    var image_source = $(".dynamic-image").first().attr('src');
    image_source = "url('" + image_source + "')";
    // Set the background
    $(".bgcover").css("background-image", image_source);

});

希望对您有所帮助。