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

如何将图片src链接赋值给img标签src属性?JS代码求助

Fix: Update Target Image's src When Clicking Another Image

Hey there! I spot the issue in your code right away—you're trying to set an image's src using the text() method, which doesn't work because src is an attribute, not text content. Let's fix this up step by step.

What Was Wrong

Your original code uses $("#img_link").text($(this).attr('src'));—but text() modifies the text inside an element, and <img> tags are self-closing (they don't have inner text). So this line does nothing to change the target image's src attribute.

Corrected Code

$(document).ready(function(){
  $(".img").click(function(){
    // Use attr() to set the src attribute of the target image
    $("#img_link").attr('src', $(this).attr('src'));
    $('#myModal').modal('hide');
  });
});

A Quick Explanation

  • $("#img_link").attr('src', $(this).attr('src')): This line grabs the src from the clicked .img element, then sets that value as the src attribute for the #img_link image. If you're using jQuery 1.6 or later, you can also use prop('src', $(this).attr('src'))—both work perfectly for this scenario.
  • The rest of your code (hiding the modal) looks fine, just make sure Bootstrap's modal JS is properly loaded so modal('hide') works as expected.

Quick Checks to Ensure It Works

  • Double-check that all your .img elements have valid src attributes.
  • Confirm the target image has the exact id img_link (no typos!).
  • Make sure Bootstrap's CSS and JS files are included in your project if you're using their modal component.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 19:57:43