I am trying to dynamically create buttons which are displayed in the 5th (last) column of a table, which is also created dynamically. Everything is created properly. However, upon clicking the buttons, the function is not triggered. Perhaps it is because I am using vue.js to develop my front-end. I have tried using "v-on:click" instead of "click" in the button.setAttribute('click', 'claim()')
code below, but this did not help.
var table = document.createElement('table')
for (var i = 1; i <= 5; i++) {
var th = document.createElement('th')
th.appendChild(header)
table.appendChild(th)
for (var j = 1; j <= 4; j++) {
var tr = document.createElement('tr')
for (var k = 1; k <= 5; k++) {
var td = document.createElement('td')
var node = document.createTextNode(k)
td.appendChild(node)
tr.appendChild(td)
if (k === 5) {
var button = document.createElement('input')
button.setAttribute('type', 'submit')
button.setAttribute('value', 'Purchase')
button.setAttribute('click', 'purchase()')
td.appendChild(button)
}
}
table.appendChild(tr)
}
You need to use addEventListener
for adding any event. Example : button.addEventListener('click', purchase)
var app = document.getElementById("app"); var table = document.createElement('table'); app.appendChild(table) for (var i = 1; i <= 5; i++) { var th = document.createElement('th') //th.appendChild(header) table.appendChild(th) for (var j = 1; j <= 4; j++) { var tr = document.createElement('tr') for (var k = 1; k <= 5; k++) { var td = document.createElement('td') var node = document.createTextNode(k) td.appendChild(node) tr.appendChild(td) if (k === 5) { var button = document.createElement('input') button.setAttribute('type', 'submit') button.setAttribute('value', 'Purchase') button.addEventListener('click', purchase) td.appendChild(button) } } table.appendChild(tr) } } function purchase() { console.log("done") }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id='app'> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.