将按钮添加到在 vue.js 中动态创建的表中

我正在尝试动态创建显示在表的第五(最后)列中的按钮,该表也是动态创建的。一切都被正确创建。但是,单击按钮后,不会触发该功能。也许是因为我使用 vue.js 来开发我的前端。我尝试在button.setAttribute('click', 'claim()')下面的代码中使用“v-on:click”而不是“click”,但这没有帮助。


  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)

  }


蝴蝶不菲
浏览 171回答 1
1回答

慕后森

您需要用于addEventListener添加任何事件。例子 :button.addEventListener('click', purchase)var app = document.getElementById("app");var table = document.createElement('table');app.appendChild(table)for (var i = 1; i <= 5; i++) {&nbsp; var th = document.createElement('th')&nbsp; //th.appendChild(header)&nbsp; table.appendChild(th)&nbsp; for (var j = 1; j <= 4; j++) {&nbsp; &nbsp; var tr = document.createElement('tr')&nbsp; &nbsp; for (var k = 1; k <= 5; k++) {&nbsp; &nbsp; &nbsp; var td = document.createElement('td')&nbsp; &nbsp; &nbsp; var node = document.createTextNode(k)&nbsp; &nbsp; &nbsp; td.appendChild(node)&nbsp; &nbsp; &nbsp; tr.appendChild(td)&nbsp; &nbsp; &nbsp; if (k === 5) {&nbsp; &nbsp; &nbsp; &nbsp; var button = document.createElement('input')&nbsp; &nbsp; &nbsp; &nbsp; button.setAttribute('type', 'submit')&nbsp; &nbsp; &nbsp; &nbsp; button.setAttribute('value', 'Purchase')&nbsp; &nbsp; &nbsp; &nbsp; button.addEventListener('click', purchase)&nbsp; &nbsp; &nbsp; &nbsp; td.appendChild(button)&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; table.appendChild(tr)&nbsp; }}function purchase() {&nbsp; console.log("done")}<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><div id='app'></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript