[英]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. 这是前置html的AJAX请求。 In a separate file i'm using a JS context menu.
在一个单独的文件中,我正在使用JS上下文菜单。 But what ever the user clicks from the context menu it does not affect the prepended html.
但是,无论用户从上下文菜单中单击什么,都不会影响前置的html。 How can I manipulate the new html element?
如何处理新的html元素? I've read something about
.on()
. 我已经阅读了有关
.on()
。
The output HTML is a table row. 输出的HTML是一个表格行。 When a user right-clicks the newly added table row this AJAX should execute:
当用户右键单击新添加的表行时,此AJAX应该执行:
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: 您可以使用所需的所有属性和属性来制作一个DOM对象,而不是字符串,然后附加/添加它们:
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. on()称为事件委托。
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. 如果要将click事件附加到javascript添加的新元素上,则需要处理新的DOM,并且应该使用事件委托。
Example bellow attach click event to the new row with class tabledata
: 以下示例将click事件附加到具有
tabledata
类的新行:
$( "body" ).on( "click", ".tabledata", function() {
//Your code here
});
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.