如何在img src属性中使用JavaScript变量?(How to use JavaScript variable in img src attribute?)

从<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>

Below JavaScript function is called after selecting option from <select> tag.

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; }

Now i want to display flag of country according to selection has made.. Below is HTML file where i want to display image..

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

I also tried this one..

<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()的开头)

You can just use

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

where myImg is your image. In your current html, it is:

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

Or you can add id attribute to your image (<img id="logo" width=30 height=30>), so you can use

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

(you should place myImg initialization at the beginning of the function1())

更多推荐

logo,country,<td><img,break,选择,电脑培训,计算机培训,IT培训"/> <meta