将 Javascript 变量放入 innerHTML 代码中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16467536/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:48:21  来源:igfitidea点击:

Put a Javascript variable into a innerHTML code

javascriptinnerhtml

提问by user1843376

I'm creating a table dynamic table with Javascript:

我正在用 Javascript 创建一个表动态表:

var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);

I want to fill the cell5 with some innerHTML with a Javascript variable inside

我想用一些内部 HTML 填充 cell5,里面有一个 Javascript 变量

var add = aux[i].split("#");
cell5.innerHTML = "<img src='MatrixLogos/add[3]' width='100' height='25'/>";

but this give add[3] in the html instead of the value inside add[3].

但这在 html 中给出了 add[3] 而不是 add[3] 中的值。

My question is how to escape the variable inside the innerHTML code, so it shows me is value and not the declaration.

我的问题是如何转义innerHTML 代码中的变量,所以它显示我是值而不是声明。

回答by parnas

Use "+".

使用“+”。

var add = aux[i].split("#");
cell5.innerHTML = "<img src='MatrixLogos/"+add[3]+"' width='100' height='25'/>";

回答by Kailash Yadav

Use Stringconcatenation like

使用String连接像

var add = aux[i].split("#");
var string = "This is to " + add[3] + " test with value";

Where as in your case, statement will become:

在您的情况下,声明将变为:

cell5.innerHTML = "<img src='MatrixLogos/"+add[3]+"' width='100' height='25'/>";