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

如何点击div内的按钮获取该div对应图片的src属性?

解决方案:点击按钮获取同容器内图片的src属性

方法一:事件委托(推荐,支持动态添加元素)

利用事件冒泡特性,给最外层容器绑定一次点击事件即可处理所有按钮的逻辑,适配后续动态新增的元素:

<div class="container">
  <div class="inner-container">
    <img src="fn4703gr5e" alt="">
    <button>Get image source from only the image inside of this div</button>
  </div>
  <div class="inner-container">
    <img src="7876jyhygfd" alt="">
    <button>Get image source from only the image inside of this div</button>
  </div>
  <div class="inner-container">
    <img src="mnbv5433sda" alt="">
    <button>Get image source from only the image inside of this div</button>
  </div>
</div>

<script>
const container = document.querySelector('.container');
container.addEventListener('click', function(e) {
  // 确认点击目标是按钮
  if (e.target.tagName === 'BUTTON') {
    // 向上查找最近的inner-container容器
    const innerContainer = e.target.closest('.inner-container');
    // 获取容器内图片的src属性
    const imgSrc = innerContainer.querySelector('img').src;
    // 这里替换为你的业务逻辑,比如打印或使用该src
    console.log(imgSrc);
  }
});
</script>

方法二:直接给每个按钮绑定事件

如果页面元素不会动态新增,可直接遍历所有按钮绑定点击事件:

<!-- HTML结构同上 -->
<script>
const buttons = document.querySelectorAll('.inner-container button');
buttons.forEach(button => {
  button.addEventListener('click', function() {
    // 通过父元素定位同容器内的图片
    const img = this.parentElement.querySelector('img');
    console.log(img.src);
  });
});
</script>

关键逻辑说明

  • closest('.inner-container'):从当前元素向上查找最近的匹配父容器,比parentElement更灵活,即使容器层级调整也能适配。
  • 事件委托优势:无需遍历所有按钮,性能更优,且后续动态添加的.inner-container按钮会自动生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:50:41