如何以更简单的方式在图像标签中编码变量?

How could I code a variable in an image tag a Simpler way?

我可能想显示同一股票代码的不同版本图表,因此需要使用 "var"。 (我的其他用途是天气图或交通摄像头等,所以我有更广泛的应用)。 我将用股票图表来说明。

通过反复试验,我发现使用 id="x" 和 "document.getElementById" 是可行的, 但它需要在每一行上仔细记录 SAME 和唯一 ID TWICE。 (打破这条线而不是 "long line" 使得保持 id 的直线更难)

想象一下,如果有几十行额外的图表变体,它会变得乏味。

有没有更好的方法?您将如何编写代码以生成 "collage of graphs"?

<script> var sym = "MSFT" </script> 

<h1><strong> <body> Symbol <script> document.write(sym); </script></body><br> 


<img src="" id="i1">$ <script> var a = document.getElementById('i1'); a.src = "http://www.google.com/finance/chart?cht=o&tlf=12h&q=" + sym ; </script> &nbsp;&nbsp;

<img src="" id="i2">% <script> var a = document.getElementById('i2'); a.src = "http://www.google.com/finance/chart?cht=c&tlf=12h&q=" + sym ; </script> &nbsp;&nbsp;
<!-- etc.  perhaps dozens more different charts for the same symbol -->

我会从 HTML 中删除所有 <script> 标签。这使文档结构和行为逻辑保持分离。这是一个使用循环和字符串连接的示例,应该是可扩展的:

<h1 id="title"></h1>
<img src="" class="symbol" alt="stock chart">$&nbsp;&nbsp;
<img src="" class="symbol" alt="stock chart">%&nbsp;&nbsp;
<!-- etc.  perhaps dozens more different charts for the same symbol -->

<script>

const sym = "MSFT";
const urls = [
  "http://www.google.com/finance/chart?cht=o&tlf=12h&q=", 
  "http://www.google.com/finance/chart?cht=c&tlf=12h&q="
];
document.getElementById("title").innerHTML = "Symbol " + sym;
const symElems = document.getElementsByClassName("symbol");

for (let i = 0; i < symElems.length; i++) {
  symElems[i].src = urls[i] + sym; 
}

</script>

您可能希望为 URL 使用对象而不是数组,并根据需要将 ID 添加到 <img> 标记。不使用 class 名称的问题在于,您可能更容易忘记正在操作的集合中有多少元素(更不用说样式了)。您可能还希望使用 document.createElement("img") 动态生成 <img> 元素并在 JS 中设置属性:

<h1 id="title"></h1>
<div id="sym-container"></div>

<script>

const sym = "MSFT";
const urls = [
  "http://www.google.com/finance/chart?cht=o&tlf=12h&q=", 
  "http://www.google.com/finance/chart?cht=c&tlf=12h&q=",
  "http://www.google.com/finance/chart?cht=g&tlf=12h&q=",
  "http://www.google.com/finance/chart?cht=s&tlf=12h&q=" 
];
document.getElementById("title").innerHTML = "Symbol " + sym;
const symContainer = document.getElementById("sym-container");

urls.forEach(e => {
  const symElem = document.createElement("img");
  symElem.src = e + sym; 
  symContainer.appendChild(symElem);
});

</script>