【问题标题】:JS variable in jquery(ajax) appending html tagjquery(ajax)中的JS变量附加html标签
【发布时间】:2021-05-14 18:10:37
【问题描述】:

编辑(完成):我想通了。语法是<button onclick="editItem('+data[i].id+')">EDIT</button>'

我有这个,它会生成数据库中的所有对象,显示 idnameactions - 两个按钮都有不同的 onclick function,我想在其中发送 object id 以备将来使用。

我只需要一个答案如何将data[i].id 放入'<button onclick="editItem(ID)">EDIT</button>',哪种语法?

$.ajax(
    {
        type:'GET',
        url:'api',
        dataType: 'json',
        success: function(data){
            console.log(data);

            for (var i=0; i<data.length; i++) {

                var row = $(

                    '<tr>' +

                    '<td>' +
                        data[i].id +
                    '</td>' +

                    '<td>' +
                        data[i].name +
                    '</td>' +

                    '<td>' +
                    '   <button onclick="editItem(ID)">EDIT</button>' +
                    '   <button onclick="deleteItem(ID)">DELETE</button>' +
                    '</td>' +

                    '</tr>'

                );
                $('#my_table').append(row);
            }
        }
    }
);

【问题讨论】:

  • 尝试使用模板文字? &lt;button onclick="editItem(${data[i].id})"&gt;EDIT&lt;/button&gt;
  • @danu 不工作

标签: javascript jquery json ajax api


【解决方案1】:

我更倾向于将 ID 添加到按钮中为 data-attributes 并使用 delegated event handler 来处理点击

// Set up event handlers on your table to listen for button clicks
const table = $("#my_table")
  .on("click", "button[data-edit]", function(e) { // EDIT button
    const id = this.dataset.edit

    // and so on, eg...
    editItem(id)
  })
  .on("click", "button[data-delete]", function(e) { // DELETE button
    const id = this.dataset.delete

    // and so on, eg... 
    deleteItem(id)
  })
  
// Using jQuery's DOM helpers makes for more concise code IMO
$.getJSON("api")
  .done(data => table.append(data.map(({ id, name }) =>
    $("<tr>").append([
      $("<td>", { text: id }),
      $("<td>", { text: name }),
      $("<td>").append([
        $("<button>", { text: "EDIT", "data-edit": id }),
        $("<button>", { text: "DELETE", "data-delete": id })
      ])
    ])
  )))

【讨论】:

  • 感谢您的回答,仍然......我没有太多经验来实现这个。
  • @sam00vun0c 对不起,我不明白你的问题
猜你喜欢
  • 2014-12-19
  • 2013-11-09
  • 2019-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多