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

ASP.Net MVC中如何实现自动滚动到Bootstrap表格指定PropID的行

问题根因

  • 你当前的代码缺少了jQuery ID选择器必须的#前缀,导致无法正确定位到对应PropID的DOM元素
  • 如果你使用的是异步加载数据的Bootstrap Table,$(document).ready()触发时表格行还没渲染完成,也会导致获取不到元素offset

修复方案

场景1:表格是服务端直接渲染的静态表格

直接补全选择器前缀即可,修正后代码如下:

@if(ViewBag.PropID != null)
{
    <script>
        $(document).ready(function () {
            // 补全ID选择器的#前缀
            const targetElement = $('#@ViewBag.PropID');
            // 加一层元素存在判断,避免报错中断JS执行
            if (targetElement.length) {
                $('html, body').animate({
                    scrollTop: targetElement.offset().top
                }, 'slow');
            }
        });
    </script>
}

场景2:Bootstrap Table是前端异步加载渲染的

需要把滚动逻辑绑定到Bootstrap Table的load-success.bs.table事件中,确保数据渲染完成后再执行滚动:

@if(ViewBag.PropID != null)
{
    <script>
        // 假设你的表格选择器是#table,替换成你实际的表格ID
        $('#table').on('load-success.bs.table', function () {
            const targetElement = $('#@ViewBag.PropID');
            if (targetElement.length) {
                $('html, body').animate({
                    scrollTop: targetElement.offset().top
                }, 'slow');
            }
        });
    </script>
}

额外注意事项

  • 确保你要滚动到的元素确实设置了和ViewBag.PropID完全一致的id属性,注意大小写、特殊字符转义问题
  • 如果元素外层有固定定位的头部导航,可以给scrollTop的值减去导航高度,避免元素被导航遮挡:scrollTop: targetElement.offset().top - 60(60替换为你实际的导航高度)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 21:54:03