我有这个javascript,它通过ajax
加载了一些内容块var sendContainer = document.getElementById("loadForm");
sendContainer.addEventListener("click", function (event) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// Show loaded content block in result div
document.getElementById("result").innerHTML = xmlhttp.responseText;
}
};
var form = document.getElementById('ajax_send_message');
var formData = new FormData(form);
xmlhttp.open("GET", '/ajax', true);
xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xmlhttp.send(formData);
});
加载内容块
<button type="button" id="ajax_submit"">Send</button>
如何强制此addEventListener从动态加载的块中获取id(ajax_submit)
document.getElementById("ajax_submit").addEventListener("click", function (event) {
alert('WORK!');
});
答案 0 :(得分:0)
只需在XMLHttpRequest()的onreadystatechange事件侦听器中添加行。
喜欢这个
var sendContainer = document.getElementById("loadForm");
sendContainer.addEventListener("click", function (event) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// Show loaded content block in result div
document.getElementById("result").innerHTML = xmlhttp.responseText;
document.getElementById("ajax_submit").addEventListener("click", function (event) {
alert('WORK!');
});
}
};
var form = document.getElementById('ajax_send_message');
var formData = new FormData(form);
xmlhttp.open("GET", '/ajax', true);
xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xmlhttp.send(formData);
});
答案 1 :(得分:0)
你应该使用jquery $.on,就像你可以在你的页面srcipt中的任何位置编写以下代码
$(document).on('someevent', 'yourelemenid', function(){
alert('work');
});