You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决jQuery获取foreach循环内图片src为undefined并设置div背景图?

问题分析与解决方案

你遇到的imgSrc返回undefined的问题,主要源于两个关键错误:

  1. 仅获取首个元素的ID:$('.carosuelProperties').attr('id')只会拿到页面中第一个带carosuelProperties类的元素ID,无法覆盖循环生成的所有元素。
  2. ID选择器缺少#前缀:jQuery中通过ID定位元素必须用#id格式,直接写$(imgId)会被当成标签名查找,自然找不到目标元素和内部的img标签。

修正后的jQuery代码

我们需要遍历所有目标div,逐个处理背景图设置,同时优化选择逻辑:

$(document).ready(function() {
  // 遍历每个.carosuelProperties元素
  $('.carosuelProperties').each(function() {
    // 用$(this)指代当前遍历到的div,避免重复选择
    const $currentDiv = $(this);
    // 获取当前div内部img的src属性
    const imgSrc = $currentDiv.find('img').attr('src');
    // 为当前div设置背景图
    $currentDiv.css("background-image", `url(${imgSrc})`);
    // 隐藏内部img,避免重复显示(可选但推荐)
    $currentDiv.find('img').hide();
  });
});

关键优化点说明

  • 使用.each()遍历所有元素,确保循环生成的每个div都能被处理。
  • 用$(this)指向当前正在操作的元素,代码更高效且避免选择器冲突。
  • 新增隐藏内部img的逻辑,因为背景图已经代替了img的显示作用,避免页面出现重复内容。

格式化后的完整代码

@if (isset($participatingProperties) && !empty($participatingProperties) && is_array($participatingProperties))
  @foreach ($participatingProperties as $property)
    <a href="/view/property/{{ $property->property_slug or $property->id }}">
      <div class="carousel__box itemProperties col-md-4 col-sm-12">
        <h2 class="propertyTitleCaro centered white sub-header">
          <?php echo mb_strimwidth(strip_tags($property->property_name), 0, 45, '...'); ?>
        </h2>
        <p class="centered white smallerText propertyDesCaro">
          <?php echo mb_strimwidth(strip_tags($property->property_short_descript), 0, 140, '...<br><br>SEE MORE'); ?>
        </p>
        <div class="carosuelProperties" id="{{ $property->id }}">
          <img class="caroImgClass" src="{{$property->property_main_image->images_main}}" alt="{{ $property->property_name or 'No name' }}" title="{{ $property->property_name or 'No name' }}">
        </div>
      </div>
    </a>
  @endforeach
@endif

内容的提问来源于stack exchange,提问作者The Real Dude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:05:43