我有一个使用 API 调用的 Laravel 项目。当生成该行时,它有一个带有模式弹出窗口的编辑按钮。模态过去在静态时工作,但现在动态添加时出现以下错误:
id 为 editUserModal 的 Modal 尚未初始化。请 使用 data-modal-target 属性对其进行初始化。
用户表ID:
<tbody id = "userTable">
//here is where i want it to be generated
//if i add a static row here the modal does work and i get no error
</tbody>
这是 JavaScript 函数(我使用 axios ):
const drawUsers = () => {
let userTable = document.getElementById("userTable");
axios.get(API.url + API.routes.getUsers)
.then(response =>{
if(response.data.status){
response.data.data.forEach(user => {
var row = `<tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
<th scope="row" class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
${user.username}
</th>
<td class="px-6 py-4">
${user.email}
</td>
<td class="px-6 py-4">
${user.is_active}
</td>
<td class="px-6 py-4">
<button id = "editUserModal" data-modal-target="editUserModal" data-modal-toggle="editUserModal" class="focus:outline-none text-white bg-green-700 hover:bg-green-800 focus:ring-4 focus:ring-green-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-green-600 dark:hover:bg-green-700 dark:focus:ring-green-800">
Edit
</button>
<button type="button" class="focus:outline-none text-white bg-red-700 hover:bg-red-800 focus:ring-4 focus:ring-red-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-red-600 dark:hover:bg-red-700 dark:focus:ring-red-900">
Delete
</button>
</td>
</tr>`;
userTable.innerHTML += row;
});
}
})
}
除了模态之外,我正确生成了所有内容,我做错了什么?有没有更好的方法用 JavaScript 动态生成 HTML 代码?
因为它会在收到数据之前尝试获取模态 ID。
数据完成后,您需要启动模态实例。
axios.get(API.url + API.routes.getUsers)
.then(response =>{
if(response.data.status){
response.data.data.forEach(user => {
var row = `<tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
<th scope="row" class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
${user.username}
</th>
<td class="px-6 py-4">
${user.email}
</td>
<td class="px-6 py-4">
${user.is_active}
</td>
<td class="px-6 py-4">
<button id = "editUserModal" data-modal-target="editUserModal" data-modal-toggle="editUserModal" class="focus:outline-none text-white bg-green-700 hover:bg-green-800 focus:ring-4 focus:ring-green-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-green-600 dark:hover:bg-green-700 dark:focus:ring-green-800">
Edit
</button>
<button type="button" class="focus:outline-none text-white bg-red-700 hover:bg-red-800 focus:ring-4 focus:ring-red-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-red-600 dark:hover:bg-red-700 dark:focus:ring-red-900">
Delete
</button>
</td>
</tr>`;
userTable.innerHTML += row;
});
}
})
.finally(() => {
//You need to start modal instance here!
})
就我个人而言,在找到更好的解决方案之前,我会重新加载页面,以便模态数据属性
data-modal-target="editUserModal" data-modal-toggle="editUserModal"
在页面加载时由 Flowbite 初始化。