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

如何在jQuery .html()中插入链接?解决图片链接//被识别为注释问题

Fixing the Double Slash Issue When Swapping Images in Your Poetry Page

Absolutely! You can definitely assign a full <img> tag (including URLs with double slashes //) to a JavaScript variable—this is a perfect solution to avoid the comment parsing problem you're facing.

The root of your issue is likely that you weren't properly wrapping the image URL or full tag in a string, which caused JavaScript to misinterpret the // as the start of a comment. When you encapsulate the entire <img> tag in a string (especially using modern syntax like template literals), the // is treated as part of the string content, not code.

Here's how to update your loadDreams() function with this approach:

Template literals (wrapped in backticks `) let you write multi-line strings with embedded quotes and special characters without extra escaping. This makes your code clean and easy to read:

function loadDreams() {
  $("h2").html("Dreams");
  $("h3").html("by Langston Hughes");
  // Fixed the truncated poem content too!
  $("p").html("Hold fast to dreams<br>For if dreams die<br>Life is a broken-winged bird<br>That cannot fly.<br><br>Hold fast to dreams<br>For when dreams go<br>Life is a barren field<br>Frozen with snow.");
  
  // Assign full img tag to a variable
  const poemImage = `<img src="https://example.com/langston-hughes-portrait.jpg" alt="Portrait of Langston Hughes">`;
  
  // Replace the existing image element or insert it into your container
  $("img").replaceWith(poemImage);
  // Or if you have a container div: $(".poem-image-container").html(poemImage);
}

Option 2: Use Single-Quoted Strings

If you prefer older syntax, wrapping the full <img> tag in single quotes works just as well. The single quotes ensure the double slashes and internal double quotes are treated as string content:

function loadDreams() {
  $("h2").html("Dreams");
  $("h3").html("by Langston Hughes");
  $("p").html("Hold fast to dreams<br>For if dreams die<br>Life is a broken-winged bird<br>That cannot fly.<br><br>Hold fast to dreams<br>For when dreams go<br>Life is a barren field<br>Frozen with snow.");
  
  const poemImage = '<img src="https://example.com/langston-hughes-portrait.jpg" alt="Portrait of Langston Hughes">';
  $("img").replaceWith(poemImage);
}

Key Notes:

  • Always make sure the src attribute value is wrapped in quotes (single or double) inside the <img> tag—this prevents URL parsing errors, even beyond the // issue.
  • If you were previously trying to set the src directly without quotes (e.g., src=https://example.com/img), that's what caused JavaScript to misinterpret the // as a comment. Wrapping the URL in quotes inside the string fixes this.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:18:29