function myMap() {
var addrlist = document.getElementById("addresslist");
var jsaddr = "Address Line1 <br /> Address Line 2 <br /> Address Line 3";
var addr = jsaddr.split("<br />");
//alert(addr);
var addrfinal = "";
for(var j=0;j<addr.length;j++)
{
addrfinal = addrfinal + addr[j] + "\n";
}
alert(addrfinal);
var traddr = document.createElement("tr");
var tdaddr = document.createElement("td");
var tdaddress = document.createTextNode(addrfinal);
tdaddr.appendChild(tdaddress);
traddr.appendChild(tdaddr);
addrlist.appendChild(traddr);
}
<table id="addresslist">
</table>
<input type="button" value="Click" onclick="myMap()" />
我想逐行向地址添加地址。但是当我提醒字符串它会得到“\ n”的效果,但在字符串中我无法获得“\ n”的效果
答案 0 :(得分:2)
我想逐行向地址添加地址。
在这种情况下,你只是让事情复杂化。您只需要在td
元素上使用innerHTML属性并分配您的初始字符串。
tdaddr.innerHTML = jsaddr;
检查以下示例。
function myMap() {
var addrlist = document.getElementById("addresslist");
var jsaddr = "Address Line1 <br /> Address Line 2 <br /> Address Line 3";
var traddr = document.createElement("tr");
var tdaddr = document.createElement("td");
tdaddr.innerHTML = jsaddr; // this is the change
traddr.appendChild(tdaddr);
addrlist.appendChild(traddr);
}
<table id="addresslist">
</table>
<input type="button" value="Click" onclick="myMap()" />
答案 1 :(得分:0)
您可以创建一个<br>
标记,并为表格元素分配行。
function myMap() {
var addrlist = document.getElementById("addresslist");
var jsaddr = "Address Line1 <br /> Address Line 2 <br /> Address Line 3";
var addr = jsaddr.split("<br />");
var traddr = document.createElement("tr");
var tdaddr = document.createElement("td");
for (var j = 0; j < addr.length; j++) {
if (j) {
tdaddr.appendChild(document.createElement('br'));
}
tdaddr.appendChild(document.createTextNode(addr[j]));
}
traddr.appendChild(tdaddr);
addrlist.appendChild(traddr);
}
<table id="addresslist"></table>
<input type="button" value="Click" onclick="myMap()" />
答案 2 :(得分:0)
您应该在循环内创建行,请参阅以下脚本:
function myMap() {
var addrlist = document.getElementById("addresslist");
var jsaddr = "Address Line1 <br /> Address Line 2 <br /> Address Line 3";
var addr = jsaddr.split("<br />");
//alert(addr);
var addrfinal = "";
for(var j=0;j<addr.length;j++)
{
addrfinal = addrfinal + addr[j] + "\n";
var traddr = document.createElement("tr");
var tdaddr = document.createElement("td");
var tdaddress = document.createTextNode(addr[j]);
tdaddr.appendChild(tdaddress);
traddr.appendChild(tdaddr);
addrlist.appendChild(traddr);
}
alert(addrfinal);
}
&#13;
<table id="addresslist">
</table>
<input type="button" value="Click" onclick="myMap()" />
&#13;