ZBLOG

for (const item of jsonRes) { if (item.code === 'customerInfo') { // 客户信息展示 } if (item.code === 'loan') { // 合同展示 // 找到目标父元素(假设它的ID是 "targetContainer") const targetContainer = document.getElementById('t...

如果您无法在 DOM 中找到元素的父元素,可能是因为以下几个原因:

  1. 目标父元素未加载:确保在脚本执行时,目标父元素(如 targetContainer)已经存在于 DOM 中。您可以将代码放入 DOMContentLoaded 事件监听器中,确保在文档完全加载后再执行。

  2. ID不匹配:确保您所使用的 ID 是正确的,并且没有拼写错误。检查您的 HTML 代码以确认元素确实具有该 ID。

  3. JavaScript 执行顺序:如果 JavaScript 在 DOM 元素之前执行,可能会导致查找失败。确保 JS 代码在适当的位置被调用,例如放在 <body> 的底部或者使用合适的事件处理程序。

示例解决方案

下面是一个修改过的示例,其中包含了对这些问题的检查:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>按钮示例</title>
  7. </head>
  8. <body>
  9. <!-- 假设这个 div 是我们要插入按钮容器的目标 -->
  10. <div id="targetContainer"></div>
  11. <script>
  12. // 模拟 jsonRes 数据
  13. const jsonRes = [
  14. { code: 'customerInfo' },
  15. { code: 'loan' } // 合同展示
  16. ];
  17. document.addEventListener('DOMContentLoaded', function() {
  18. for (const item of jsonRes) {
  19. if (item.code === 'customerInfo') {
  20. // 客户信息展示
  21. }
  22. if (item.code === 'loan') { // 合同展示
  23. // 找到目标父元素(假设它的ID是 "targetContainer")
  24. const targetContainer = document.getElementById('targetContainer');
  25. if (!targetContainer) {
  26. console.error('无法找到目标容器,请检查 ID 是否正确');
  27. return;
  28. }
  29. // 创建按钮容器
  30. const buttonContainer = document.createElement('div');
  31. buttonContainer.innerHTML = `
  32. <div class="button-container">
  33. <button class="btn" data-action="action1">按钮1</button>
  34. <button class="btn" data-action="action2">按钮2</button>
  35. <button class="btn" data-action="action3">按钮3</button>
  36. <button class="btn" data-action="action4">按钮4</button>
  37. </div>
  38. `;
  39. // 将按钮容器插入到目标父元素中
  40. targetContainer.appendChild(buttonContainer);
  41. buttonContainer.querySelectorAll('.btn').forEach(button => {
  42. button.addEventListener('click', function() {
  43. const action = this.getAttribute('data-action');
  44. switch (action) {
  45. case 'action1':
  46. console.log('按钮1被点击');
  47. break;
  48. case 'action2':
  49. console.log('按钮2被点击');
  50. break;
  51. case 'action3':
  52. console.log('按钮3被点击');
  53. break;
  54. case 'action4':
  55. console.log('按钮4被点击');
  56. break;
  57. default:
  58. break;
  59. }
  60. });
  61. });
  62. }
  63. }
  64. });
  65. </script>
  66. </body>
  67. </html>

关键点总结:

  • 使用 document.addEventListener('DOMContentLoaded', ...) 确保 DOM 元素已经加载完毕。
  • 检查是否能成功获取到目标元素,并提供错误日志帮助调试。
  • 确保所有 ID 和类名都是一致和准确的,以避免运行时错误。


    内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=22049

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?