【问题标题】:How to concatenate img src in html如何在html中连接img src
【发布时间】:2020-07-13 05:06:39
【问题描述】:

我的目标是创建一个包含许多图像的表格。通过这样做,我将通过一个具有该图像位置的数组。我的问题是,如何将此字符串转换为动态字符串:

 <td><img src="http://openweathermap.org/img/w/ + local.weather[0].icon +.png"></td>

“local.weather[0].icon”是动态部分。我似乎无法找到一种可行的方法。

【问题讨论】:

  • 试试src="http://openweathermap.org/img/w/" + local.weather[0].icon + ".png"
  • @AneesIjaz 我之前试过,但由于某种原因,“.png”部分没有变成字符串
  • 我猜你将不得不使用 js。
  • @AneesIjaz 我遇到了同样的错误。 “.png”部分变成白色并且不会变成字符串。我应该把“”放在哪里?还是我应该使用 ' ' ?

标签: html arrays string image


【解决方案1】:

你必须在 js 中手动完成。 (您不能在页面加载时动态添加 src 属性。为此,您必须在服务器上执行此操作或在窗口加载时通过 js 更改它) 试试下面的代码。

<td><img id="weatherImg"></td>
window.addEventListener('load', () => {
    document.getElementById("weatherImg").src = `http://openweathermap.org/img/w/${local.weather[0].icon}.png`;
});

【讨论】:

    【解决方案2】:

    使用模板字符串。

    here is the example,
    var val = 'fortnite'
    var x = 'I play ${val}';
    console.log(x);     // I play fortnite
    val = 'pubg'
    console.log(x);     // I play pubg
    //so I have made that dynamic using template strings. Use ` key instead for quotes.
    [![This is the key][1]][1]
    

    【讨论】:

    • 感谢您的回复。我明白那个。我试图在 html 元素中找到一种方法来执行此操作,而不是在 js 上执行此操作,然后将其加载到 table 上。
    猜你喜欢
    • 2016-02-11
    • 2023-03-03
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多