asp.net - 如何使用 jQuery 捕获 ASP.NET GridView 中的 'Update' 点击事件

标签 asp.net jquery gridview

我需要在 asp.net GridView 中使用 jQuery 捕获“更新”点击事件,但不知道从哪里开始。我对 jQuery 还很陌生。我的 GridView 附加到 SQLDataSource,并且自然地具有该组合提供的所有功能。任何帮助将不胜感激。

最佳答案

只需在声明 GridView 后的任何位置添加脚本 block ,它就应该与默认的非模板化 GridView 列一起使用。代码隐藏中没有代码,因为它纯粹是一个 Javascript 解决方案。

如果您使用链接类型的 GridView 列,请使用此选项:

<script type="text/javascript">
    // a:contains(The text of the link here)
    $('#<%= theGridViewID.ClientID %> a:contains(Update)').click(function () {
        alert('Update click event captured from the link!');
        // return false: stop the postback from happening
        // return true or don't return anything: continue with the postback
    });
</script>

如果您使用按钮型 GridView 列并且不希望 Javascript 阻止回发,请使用此选项:

<script type="text/javascript">
    // :button[value=The text of the button here]
    $('#<%= theGridViewID.ClientID %> :button[value=Update]').click(function () {
        alert('Update click event captured from the button!');
    });
</script>

如果您使用按钮类型的 GridView 列并且希望控制是否继续回发,请使用此选项:

<script type="text/javascript">
    // :button[value=The text of the button here]
    var updateButtons = $('#<%= theGridViewID.ClientID %> :button[value=Update]');
    updateButtons
        .attr('onclick', null)
        .click(function () {
            alert('Update click event captured from the button!');
            var doPostBack = true; // decide whether to do postback or not
            if (doPostBack) {
                var index = updateButtons.index($(this));
                // 'Update$' refers to the GridView command name + dollar sign
                __doPostBack('<%= theGridViewID.UniqueID %>', 'Update$' + index);
            }
        });
</script>
<小时/>

更新:我认为这将是替换我上面介绍的最后一个(第三个)脚本 block 的更好的解决方案,因为您不需要根据以下内容手动更新 __doPostBack 函数调用命令名称,因此,它应该不太容易出错:

<script type="text/javascript">
    // :button[value=The text of the button here]
    var updateButtons = $('#<%= theGridViewID.ClientID %> :button[value=Update]');
    updateButtons.each(function () {
        var onclick = $(this).attr('onclick');
        $(this).attr('onclick', null).click(function () {
            alert('Update click event captured from the button!');
            var doPostBack = true; // decide whether to do postback or not
            if (doPostBack) {
                onclick();
            }
        });
    });
</script>

这个想法要归功于 Aristos。 :)

关于asp.net - 如何使用 jQuery 捕获 ASP.NET GridView 中的 'Update' 点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2588036/

相关文章:

javascript - 数据保存后、重定向到同一页面(或刷新)之前显示“确定”对话框

asp.net - 如何访问母版页中的枚举

javascript - jQuery 内部服务器错误

javascript - 使用 jQuery 单击时垂直滚动 100%

javascript - 如何使用 jQuery Validate 的 Angular 实现来应用类级别验证规则

ASP.NET 事件未在包含大型 GridView 控件的页面中触发

asp.net - Entity Framework 4.0 附加对象图

asp.net - TeamCity 构建任务以自动启动 ASP.NET 网站

javascript - Asp.net 在 gridview 页脚中显示列总数

c# - 如何向 devexpress gridcontrol 添加自定义摘要项