Javascript внутренний HTML: кнопка не работает внутри таблицы - PullRequest
0 голосов
/ 23 апреля 2020

Я добавил кнопку внутри своей внутренней таблицы HTML, кнопка в первом ряду работает, но последующие не работают.

HTML:

<p id="stat_tbl"></p>

Javascript:

let tbl = document.getElementById("stat_tbl")

var txt = ""
txt += "<table>"
txt += "<tr><th>Name</th><th>Code</th></tr>"
for(x in obj) {
    txt += "<tr><td> + obj[x].name + </td>"
    txt += "<td><button type='' id='btnclick' onclick='tes()' value='" + obj[x].code + "'>Show Code</button></td></tr>"
}
txt += "</table>"

tbl.innerHTML = txt

Я пытался:

let btn = document.createElement("button")

txt += "<td>" + btn + "</td></tr>"

tbl.appendChild(btn)

, но вывод = [object HTMLButtonElement]

Ответы [ 4 ]

0 голосов
/ 23 апреля 2020
  1. создать действительный html
  2. делегировать нажатие кнопки

const obj = {a: {name: 'aObj', code: 'A'}, b: {name: 'bObj', code: 'B'}};
const tbl = document.getElementById("stat_tbl")
var txt = []
txt.push("<table><thead><tr><th>Name</th><th>Code</th></tr></thead><tbody>");
for (x in obj) {
  txt.push("<tr><td>" + obj[x].name + "</td>");
  txt.push("<td><button type='button' class='show' value='" + obj[x].code + "'>Show Code</button></td></tr>");
}
txt.push("</tbody></table>");

tbl.innerHTML = txt.join("");

tbl.addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.classList.contains("show")) {
    console.log(tgt.value);
  }
});
<p id="stat_tbl"></p>

Использование литералов шаблона

const obj = {a: {name: 'aObj', code: 'A'}, b: {name: 'bObj', code: 'B'}};
const tbl = document.getElementById("stat_tbl")
var txt = []
txt.push(`<table><thead><tr><th>Name</th><th>Code</th></tr></thead><tbody>`);
for (x in obj) {
  txt.push(`<tr><td>${obj[x].name}</td>`);
  txt.push(`<td><button type='button' class='show' value='${obj[x].code}'>Show Code</button></td></tr>`);
}
txt.push(`</tbody></table>`);

tbl.innerHTML = txt.join("");

tbl.addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.classList.contains("show")) {
    console.log(tgt.value);
  }
});
<p id="stat_tbl"></p>
0 голосов
/ 23 апреля 2020

Кнопка без какого-либо типа (кнопка или отправить) работает как кнопка отправки. Так как формы нет, ничего не будет отправлено.

Вы можете использовать атрибуты другой кнопки для своей.

let btn = document.createElement("button");
btn.type = 'button';
btn.onclick = tes; // the function tes() must be declared
btn.value = 'Click me';

// Better use DOM here
// txt += "<td>" + btn + "</td></tr>";

let td = document.createElement('td');
td.appendChild(btn);

let tr = document.createElement('tr');
tr.appendChild(td);

tbl.appendChild(tr);
0 голосов
/ 23 апреля 2020

Существует несколько способов решения этой проблемы в вашем коде.

Основы, не очень эффективный, но работает, подход, когда обработчик onclick встроен, вы можете передать event для обработки щелчка , А затем возьмите ссылку на кнопку с помощью event.target.

. Не устанавливайте одинаковые id для таких элементов, как id='btnclick', в этом нет смысла.

let tbl = document.getElementById("stat_tbl")
let obj = {a: {name: 'aObj', code: 'A'}, b: {name: 'bObj', code: 'B'}};
var txt = ""
txt += "<table>"
txt += "<tr><th>Name</th><th>Code</th></tr>"
for(x in obj) {
    txt += "<tr><td>" + obj[x].name + "</td>"
    txt += "<td><button type='' onclick='tes(event)' value='" + obj[x].code + "'>Show Code</button></td></tr>"
}
txt += "</table>"

tbl.innerHTML = txt

function tes(ev) {
 console.info(ev.target.value);
} 
<p id="stat_tbl"></p>
0 голосов
/ 23 апреля 2020

Измени свой на l oop вот так, это работа для меня.

for(let x in obj) {
    txt += "<tr><td>" + obj[x].name + "</td>"
    txt += "<td><button type='' id='btnclick' onclick='tes()' value='" + obj[x].code + "'>Show Code</button></td></tr>"
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...