如何在img src属性中使用JavaScript变量

How to use JavaScript variable in img src attribute?

本文关键字:JavaScript 变量 属性 img src      更新时间:2023-09-26

<select>标记中选择选项后,将调用下面的JavaScript函数。

function function1()
{
var country=document.getElementById('id1').value;
switch(country)
{
 case "India":
     logo="rupee.png";
     break;
 case "US":
     logo="dollar-logo.png";
     break;
 case "Britan":
      logo="yen.png";
      break;
}

现在我要展示的国家的国旗已经选定。。下面是我想要显示图像的HTML文件。。

<td><img src="+logo+" width=30 height=30></td>

我也试过这个。。

<td><img src="<%Eval(logo)%>" width=30 height=30></td>

您只需使用

case "India":
     myImg.src="rupee.png";
     break;
case "US":
     myImg.src="dollar-logo.png";
     break;
case "Britan":
     myImg.src="yen.png";
     break;

其中myImg是您的图像。在您当前的html中,它是:

var myImg = document.getElementsByTagName("img")[0];

或者您可以将id属性添加到您的图像(<img id="logo" width=30 height=30>)中,这样您就可以使用

var myImg = document.getElementById("logo");

(您应该将myImg初始化放在function1()的开头)

您可以使用JS 设置属性

function function1()
   {
   var country=document.getElementById('id1').value;
    switch(country)
      {
      case "India":
      logo="rupee.png";
      break;
      case "US":
      logo="dollar-logo.png";
      break;
      }
    document.getElementsByTagName("img")[0].src = logo;
   }