我到处寻找这个解决方案,但找不到可以帮助我的答案。我的标签是用数据库中的 ajax 以这种方式呈现的代码:
function all() {
// Ajax config
$.ajax({
type: "GET", //we are using GET method to get all record from the server
url: 'all.php', // get the route value
success: function (response) {//once the request successfully process to the server side it will return result here
// Parse the json result
response = JSON.parse(response);
var html = "";
// Check if there is available records
if(response.length) {
html += '<div class="list-group">';
// Loop the parsed JSON
$.each(response, function(key,value) {
// Our employee list template
html += '<a href="#" class="list-group-item list-group-item-action">';
html += "<p class='m-0'>" + value.let_txt_3 + "</p>";
html += "<p class='m-0'>" + value.let_txt_4 + "</p>";
html += "<p class='m-0'>" + value.let_txt_5 + "</p>";
html += "<p class='m-0'>" + value.let_txt_6 + "</p>";
html += "<button type='button' class='btn btn-primary' data-bs-toggle='modal' data-bs-target='#edit-employee-modal' id='edit_employee_modal' data-bs-id='"+value.id+"'>Edit</button>";
html += '</a>';
});
html += '</div>';
} else {
html += '<div class="alert alert-warning">';
html += 'No records found!';
html += '</div>';
}
// Insert the HTML Template and display all employee records
$("#employees-list").html(html);
}
});
}
我想操作 html 按钮,但我不能。
html += "<button type='button' class='btn btn-primary' data-bs-toggle='modal' data-bs-target='#edit-employee-modal' id='edit_employee_modal' data-bs-id='"+value.id+"'>Edit</button>";
例如,帮助我执行以下操作:
- 当您按下按钮显示
alert("test");
- 或者
edit_employee_modal.style.color = "red";
我的问题是我不知道这个错误,inspect
-> console
(点击按钮):
modal.js:332 Uncaught TypeError: Cannot read properties of undefined (reading 'classList')
at De._isAnimated (modal.js:332:26)
at De._initializeBackDrop (modal.js:205:24)
at new De (modal.js:82:27)
at De.getOrCreateInstance (base-component.js:55:41)
at HTMLButtonElement.<anonymous> (modal.js:434:22)
at HTMLDocument.n (event-handler.js:120:21)
我试过什么?!
let edit_employee_modal = document.querySelector("#edit_employee_modal");
edit_employee_modal.onclick = function() {
edit_employee_modal.style.color = "red";
}
页面加载后尝试执行脚本:
window.document.onload = function(e){
let edit_employee_modal = document.querySelector("#edit_employee_modal");
edit_employee_modal.onclick = function() {
edit_employee_modal.style.color = "red";
}
}
我用下面的代码替换了它,它也不起作用(因为我认为 javascript 无法读取我的标签):
window.onload = function(e){
//code
}
document.addEventListener("DOMContentLoaded", function(event) {
// code
});
你能帮我出主意吗?
ps:我是新手,不要评价太苛刻
我们如何获取数据并不重要,重要的是在元素(按钮)被添加到 DOM 之后对其进行引用。
onclick
当我们在加载的数据中显式设置属性时,有一种简单的老式方法:如果您想在添加 HTML 后分配处理程序,那么您可以这样做:
在您的情况下,您需要在 之后添加处理程序
$("#employees-list").html(html)
,因为 html() 方法不是异步的。