简体   繁体   中英

JS variable in jquery(ajax) appending html tag

EDIT (done) : I figure it out. Syntax is <button onclick="editItem('+data[i].id+')">EDIT</button>'

I have this, it generates all the objects in database, showing id , name and actions - both buttons have different onclick function where i want to send object id for future things.

I just need an answer how to put data[i].id in '<button onclick="editItem(ID)">EDIT</button>' , which syntax?

$.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);
            }
        }
    }
);

I'd be more inclined to add the ID to the buttons as data-attributes and use a delegated event handler to handle the clicks

// 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 })
      ])
    ])
  )))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM