我需要在asp.net GridView中使用jQuery捕获’Update’单击事件,并且无法知道从哪里开始.我还是jQuery的新手.我的GridView附加到sqlDataSource,当然,它具有组合提供的所有功能.任何帮助将不胜感激.
解决方法
只需在声明GridView后的任何位置添加脚本块,它应该使用默认的非模板化GridView列.代码隐藏中没有代码,因为它纯粹是一个
Javascript解决方案.
如果您使用的是Link-type 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>
如果您使用的是Button类型的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>
如果您使用的是Button类型的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>
更新:我认为这将是替换上面提到的最后一个(第三个)脚本块的更好的解决方案,因为您不需要根据命令名称手动更新__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这个想法.