i did a table that include id name and link. I want to make a link take to the page that it is assigned to when you click it. I tried different ways but it doesn't work.
so i want my links to take to the page when you click it
here is what i got so far
var companies = [
{
id: 1,
name: 'Google',
link: 'http://google.com/'
},
{
id: 2,
name: 'Microsoft',
link: 'http://microsoft.com/'
},
{
id: 3,
name: 'Apple',
link: 'http://apple.com'
}
];
var tbl = document.createElement("table");
var thead = document.createElement("thead");
var tbody = document.createElement("tbody");
var tr_head = document.createElement("tr");
var th_id = document.createElement("th");
var th_name = document.createElement("th");
var th_link = document.createElement("th");
th_id.textContent = "Id";
th_name.textContent = "Name";
th_link.textContent = "link";
tr_head.appendChild(th_id);
tr_head.appendChild(th_name);
tr_head.appendChild(th_link);
thead.appendChild(tr_head);
for(var i = 0; i < companies.length; i++) {
var tr_body = document.createElement("tr");
var td_id = document.createElement("td");
var td_name = document.createElement("td");
var td_link = document.createElement("td");
var id = companies[i].id;
var name = companies[i].name;
var link = companies[i].link;
//link-------------------
var a = document.createElement('a');
a.setAttribute("href", link);
td_link.appendChild(a);
td_id.textContent = id;
td_name.textContent = name;
td_link.textContent = link;
tr_body.appendChild(td_id);
tr_body.appendChild(td_name);
tr_body.appendChild(td_link);
tbody.appendChild(tr_body);
//css----------------------
td_id.style.padding = "10px";
td_id.style.border = "1px solid black";
td_name.style.padding = "10px";
td_name.style.border = "1px solid black";
td_link.style.padding = "10px";
td_link.style.border = "1px solid black";
}
//css -----------
tbl.style.border = "1px solid black";
th_id.style.padding = "10px";
th_id.style.border = "1px solid black";
th_name.style.padding = "10px";
th_name.style.border = "1px solid black";
th_link.style.padding = "10px";
th_link.style.border = "1px solid black";
tbl.appendChild(thead);
tbl.appendChild(tbody);
console.log(tbl);
document.body.appendChild(tbl);
答案 0 :(得分:1)
我同意Parag Datar,但此处给出的答案https://stackoverflow.com/a/4772817/3204135将涵盖缺失的链接文字。 在您的代码中,它可能看起来像这样:
var a = document.createElement('a');
a.setAttribute("href", link);
var linkText = document.createTextNode(link);
a.appendChild(linkText);
td_link.appendChild(a);
答案 1 :(得分:-1)
删除td_link.textContent = link;
行,你很好!