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

如何获取对应区块ImageUrl输入框值以实现背景图切换?

问题解决:独立获取每个区块的ImageUrl值

你的代码问题在于全局选择器$(".ImageUrl")——它会匹配页面上所有带ImageUrl类的输入框,jQuery默认返回第一个匹配元素的值。这就导致操作第二个区块按钮时,要么拿到第一个输入框的undefined(未输入时),要么错误复用第一个输入框的值。

要解决这个问题,你需要基于当前点击的按钮,限定查找范围到它所在的区块内部:

jQuery($ => {
  $(".Btn").click(function() {
    // 先获取当前点击按钮所在的父区块
    const $parent = jQuery(this).closest('.parent');
    // 在当前区块内找对应的ImageUrl输入框和child元素
    const imageUrl = $parent.find(".ImageUrl").val();
    $parent.find('.child').css("backgroundImage", `url('${imageUrl}')`);
  });
});

关键逻辑说明

  • jQuery(this).closest('.parent'):从当前点击的.Btn元素出发,向上查找最近的.parent容器,把操作范围严格限定在当前区块内。
  • $parent.find(".ImageUrl"):只在当前.parent容器内查找输入框,确保拿到的是当前区块的URL值,完全避免跨区块干扰。

完整可运行代码如下:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="parent">
    <div class="child">
    </div>
    <div class="switch">
      <input class="ImageUrl"> <span class="Btn">Go</span>
    </div>
  </div>
</div>

<div class="wrapper">
  <div class="parent">
    <div class="child">
    </div>
    <div class="switch">
      <input class="ImageUrl"> <span class="Btn">Go</span>
    </div>
  </div>
</div>
.child {
  width: 300px;
  height: 300px;
  background: #ccc;
  background-size: cover;
}

.wrapper {
  width: 300px;
  float: left;
  margin-left: 20px;
}
jQuery($ => {
  $(".Btn").click(function() {
    const $parent = jQuery(this).closest('.parent');
    const imageUrl = $parent.find(".ImageUrl").val();
    $parent.find('.child').css("backgroundImage", `url('${imageUrl}')`);
  });
});

内容的提问来源于stack exchange,提问作者Jerry

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:15:49