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

使用jQuery实现:保存用户输入图片链接并填充至img标签src属性

解决Superhero Cards Maker的图片链接获取与卡片生成问题

问题分析

  • 你当前用let image = $('.input')选中的是包含输入框的div容器,并非输入框元素,因此无法获取用户输入的图片链接,需选中id为input的输入框并调用.val()方法取值。
  • 每次调用$(".card").append()会给页面上所有.card元素重复添加内容,需仅对刚插入的新卡片进行操作。
  • 生成img标签时未将获取到的图片链接赋值给src属性。

修改后的完整代码

<!DOCTYPE html>
<html>
  <head>
    <title>Superhero Cards Maker</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  </head>
  <body>
    <h2 id="h2">Superhero Cards Maker</h2>
    <div class="input">
      <label>Put the link of your image </label>
      <input id="input" type="text" placeholder="https://images.hdqwalls.com/download/i-am-iron-man-avengers-endgame-5k-4r-1280x720.jpg"
      />
    </div>
    <div class="options">
      <button class="submit-btn">Submit</button>
      <button id="add-card">Add Card</button>
    </div>
    <div class="cards-template">
      <div class="card"></div>
    </div>
    <div class="cardbook"></div>
  </body>
  <script>
    $(".cards-template").hide();
    function addCard() {
      // 获取输入框中的图片链接,去除首尾空格
      let imageUrl = $('#input').val().trim();
      // 克隆模板卡片并插入到cardbook最前面
      let newCard = $(".cards-template .card").clone();
      $(".cardbook").prepend(newCard);
      
      // 向新卡片中添加内容,并设置图片src
      let cardContent = `
        <h3 class="title" contenteditable="true">Type the name of your hero here (delete this)</h3>
        <p class="content" contenteditable="true">Type the description here (delete this)</p>
        <img src="${imageUrl || ''}" alt="Superhero Image">
      `;
      newCard.append(cardContent);
      
      // 清空输入框,方便下次输入
      $('#input').val('');
    }
    $("#add-card").click(addCard);
  </script>
</html>

关键修改说明

  • 正确获取输入值:使用$('#input').val()定位输入框并获取内容,.trim()过滤首尾空格,避免无效空链接。
  • 操作单个新卡片:通过clone()复制模板卡片元素并保存到变量,仅对该新元素添加内容,避免影响已存在的旧卡片。
  • 设置图片链接:利用模板字符串将获取到的imageUrl赋值给img标签的src属性,同时添加alt属性优化页面可访问性。
  • 体验优化:添加清空输入框的逻辑,简化用户后续操作流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:35:11