gpt4 book ai didi

javascript - 单击监听器以 ajax 加载内容。纯javascript

转载 作者:行者123 更新时间:2023-11-28 10:48:30 25 4
gpt4 key购买 nike

我有这个 javascript,它通过 ajax 加载了一些内容 block

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

并加载内容 block

<button type="button" id="ajax_submit"">Send</button>

如何强制此 addEventListener 从动态加载的 block 中获取 id (ajax_submit)

document.getElementById("ajax_submit").addEventListener("click", function (event) {
alert('WORK!');

});

最佳答案

只需在 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);
});

关于javascript - 单击监听器以 ajax 加载内容。纯javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38764645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com