我做了一個包含id名和鏈接的表。我想在點擊它時將鏈接帶到分配給它的頁面。我嘗試了不同的方式,但它不起作用。javascript DOM-add href和<a>鏈接
,所以我想,當你點擊它
這是我走到這一步,
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);