You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript开发日历时onclick点击事件不生效是什么原因?

问题原因

  • 动态生成的td元素没有在创建时绑定点击事件,你写在全局的td.setAttribute代码找不到对应的td变量,自然不会生效
  • 事件绑定的函数名、参数都写错了:你定义的函数是myFunction,不是random,字符串形式的参数也没有加引号,变量element也不存在

修复步骤

  1. 找到showCalendar函数中生成有效日期单元格的代码段,在创建cell后直接绑定点击事件
  2. 删除全局作用域下无效的td.setAttribute("onclick", "random(element, red)")代码

修改后的showCalendar函数核心代码

else {
    let cell = document.createElement("td");
    let cellText = document.createTextNode(date);
    if (date === today.getDate() && year === today.getFullYear() && month === today.getMonth()) {
        cell.classList.add("bg-info");
    } 
    // 新增点击事件绑定
    cell.addEventListener('click', function() {
        // 测试修改颜色逻辑
        myFunction(this, 'red');
        // 后续要加模态框逻辑直接写在这里即可
    })
    cell.appendChild(cellText);
    row.appendChild(cell);
    date++;
}

扩展:实现点击弹出Bootstrap模态框

你已经引入了Bootstrap相关依赖,直接用自带的模态框组件即可:

  1. 在HTML中添加模态框结构,放在容器div.container内的任意位置即可:
<!-- 日期选择模态框 -->
<div class="modal fade" id="dateModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">日期详情</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        你选中的日期是:<span id="pickedDate"></span>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>
  1. 修改点击事件逻辑,触发模态框显示:
cell.addEventListener('click', function() {
    myFunction(this, 'red');
    // 填充日期内容
    document.getElementById('pickedDate').textContent = `${year}年${months[month]}${date}日`;
    // 弹出模态框
    $('#dateModal').modal('show');
})

内容的提问来源于stack exchange,提问作者CrazyKanav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 06:54:01