When creating a table with JS and having a button inside that table, with an eventListener on that button, the event just won't be triggered when clicking the button. I am calling this function inside a forEach-Loop to dynamically build my table, and apply the event-Listener for each button.
Here's my original code:
static createList(item) {
let table = document.getElementById("rows")
let row = table.insertRow();
let cell_1 = row.insertCell();
cell_1.innerHTML = item.id_recipient_sms;
let cell_2 = row.insertCell();
cell_2.innerHTML = '<input type="text" placeholder="' + item.phone_number + '" id="smsRecipient' + item.id_recipient_sms + '">';
var inputElement = document.createElement('input');
inputElement.type = 'button';
inputElement.id = item.id_recipient_sms;
inputElement.addEventListener('click', function() {
console.log(item.id_recipient_sms)
});
let cell_3 = row.insertCell();
cell_3.appendChild(inputElement);
}
Which is not working in my program. I created a code snippet, which is working, though. Can it have sth to do with the addEventListener within the loop? I still can't find the misstake in my original code.
let table = document.getElementById("rows")
let row = table.insertRow();
let cell_1 = row.insertCell();
cell_1.innerHTML = "cell1";
let cell_2 = row.insertCell();
cell_2.innerHTML = "cell2";
var inputElement = document.createElement('input');
inputElement.type = 'button';
inputElement.addEventListener('click', function() {
alert("It Works here");
});
let cell_3 = row.insertCell();
cell_3.appendChild(inputElement);
<table id="rows">
</table>
答案 0 :(得分:0)
答案 1 :(得分:0)
You haven't called the function in the code. That is why it doesn't work. Instead inside the script tag or in the external js file, add the code without function
var countries = new List<string>
{
"Afghanistan",
"Albania",
"Algeria",
"El Salvador",
"Equatorial",
"Guinea",
"Eritrea",
"Estonia",
"Ethiopia",
"Panama",
"Papua",
"Paraguay",
"Peru",
"Togo",
"Trinidad & Tobago",
"Tunisia",
"Turkey"
};
var filters = new List<string> {"tan", "ia", "Tu"};
var result = countries.Where(country => filters.Any(filter => country.Contains(filter)));
foreach (var resultItem in result)
{
Console.WriteLine(resultItem);
}
Console.ReadKey();
This worked?