简体   繁体   中英

Issue manipulating appended html elements

I saw some similar questions but still can't get it.

$(function () {
  var csrf = $('input[name=_token]').val();
  $.ajax({
       async: false,
       url: "../public/currentfile",                   
       dataType: 'json',
       method:'POST',
       data: {"_token": csrf},
       complete: function(data) {
            console.log(data.responseJSON); 
            var created_at = data.responseJSON['created_at'];
            var filesize = data.responseJSON['filesize'];
            var filename = data.responseJSON['filename'];
            var fileid = data.responseJSON['fileid'];
            $("#results .toBeSelected").prepend("<tr class='tabledata newdata'><td>" + fileid + "</td><td>" + filename + "</td><td>" + filesize + "</td><td>" + created_at + "</td></tr>");
       }                    
  });
});

This is the AJAX request that prepends the html. In a separate file i'm using a JS context menu. But what ever the user clicks from the context menu it does not affect the prepended html. How can I manipulate the new html element? I've read something about .on() .

The output HTML is a table row. When a user right-clicks the newly added table row this AJAX should execute:

function getImage(){
    var classElements = document.querySelectorAll("tr.ui-selected td.filename");
    var csrf = $('input[name=_token]').val();

    var result;
    result = classElements[0].innerHTML;
    $.ajax({
        async: true,                      
        method: 'POST',
        dataType: 'json',
        url: '../public/selecteduserfiles',
        data: {filename: result, "_token": csrf},
        complete: function(response) {
            console.log(response.responseJSON);                  
            $("img.getImage").attr('src', response.responseJSON);                
        }
    });
});

Instead of a string, you can make a DOM object with all properties and attributes you need and then append/prepend them:

var domObj = $('<tr/>')
                 .addClass('tabledata newdata')
                 .append('<td>" + fileid + "</td><td>" + filename + "</td><td>" + filesize + "</td><td>" + created_at + "</td>')
                 .on('click', function() { /* do something */ });
$("#results .toBeSelected").prepend(domObj);

The on() is called event delegation.

Description: Attach an event handler function for one or more events to the selected elements.

If you want to attach click event to the new elements added by javascript then you deal with fresh DOM and you should use event delegation.

Example bellow attach click event to the new row with class tabledata :

$( "body" ).on( "click", ".tabledata", function() {
    //Your code here
});

Hope this helps.

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