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

如何实现表格单元格添加5个项目后禁用模态框弹出?

解决思路及方案

你的代码无法阻止模态框弹出,核心原因是Bootstrap的模态框触发逻辑是通过事件委托绑定在document层面的——即使你在<td>的onclick里调用event.stopPropagation(),事件依然会冒泡到document,触发Bootstrap内置的模态框打开逻辑。

下面给两种可行的解决方法:

方法一:Blade模板层面条件控制触发属性

直接在模板里判断项目数量,只有当项目数≤5时,才添加Bootstrap模态框的触发属性:

<td {{ count($jad) <= 5 ? 'data-toggle="modal" data-target="#CalenderModalNew"' : '' }}>
    @foreach ($jad as $jadu)
      {{ $jadu }}
    @endforeach
</td>

这种方式最简单,当项目数超过5时,<td>没有触发模态框的属性,自然不会弹出模态框。

方法二:JavaScript手动控制模态框显示

如果需要保留更多交互灵活性,可以移除<td>上的data-toggle和data-target,改用JS监听点击事件:

Blade代码:

<td class="calendar-cell" data-item-count="{{ count($jad) }}">
    @foreach ($jad as $jadu)
      {{ $jadu }}
    @endforeach
</td>

JavaScript代码(适配Bootstrap 5+):

// 监听所有日历单元格的点击事件
document.querySelectorAll('.calendar-cell').forEach(cell => {
    cell.addEventListener('click', function() {
        const itemCount = parseInt(this.dataset.itemCount);
        // 只有项目数≤5时才打开模态框
        if (itemCount <= 5) {
            const modal = new bootstrap.Modal(document.getElementById('CalenderModalNew'));
            modal.show();
        }
    });
});

如果用jQuery(适配Bootstrap 3/4):

$('.calendar-cell').on('click', function() {
    const itemCount = parseInt($(this).data('item-count'));
    if (itemCount <= 5) {
        $('#CalenderModalNew').modal('show');
    }
});

内容的提问来源于stack exchange,提问作者M. Rivaldi Anwar Putra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 05:42:51