我想将 javascript 变量分配给 javascript 中的 html 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11132132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I want to assign javascript variable to html element inside javascript
提问by Dhinesh.B
I'm trying to insert javascript variable value in html element inside javascript.. But it's not working properly.. following are my code..
我正在尝试在 javascript 内的 html 元素中插入 javascript 变量值.. 但它不能正常工作.. 以下是我的代码..
window.onload = function() {
var image=document.getElementById('img').value;
var img = '<div id="pic"><img src="image" width="200" height="108" /><p></p></div>';
}
This is the function. Here i'm getting image in variable image.. i'm trying to assign this image to in one div id pic.. there i'm assigning src="image" which i got in var image.. But its not working..
这就是功能。在这里,我正在获取可变图像中的图像。 .
回答by Blender
You need to insert the value into the string:
您需要将值插入到字符串中:
var img = '<div id="pic"><img src="' + image + '" width="200" height="108" /><p></p></div>';
回答by Laughing
it should be like this:
它应该是这样的:
var img = '<div id="pic"><img src="'+image+'" width="200" height="108" /><p></p></div>';
回答by Alvin Wong
I think you should do this instead:
我认为你应该这样做:
window.onload = function() {
var image=document.getElementById('img').value;
document.getElementById('pic').innerHTML='<img src="'+image+'" width="200" height="108" /><p></p>';
}