Put a Javascript variable into a innerHTML code

﹥>﹥吖頭↗ 提交于 2019-12-18 16:57:46

问题


I'm creating a table dynamic table with 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

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].

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


回答1:


Use "+".

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



回答2:


Use String concatenation like

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'/>";


来源:https://stackoverflow.com/questions/16467536/put-a-javascript-variable-into-a-innerhtml-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!