How to attach a jQuery event to a grid view that is not visible on document ready?

a 夏天 提交于 2020-01-16 08:28:13

问题


I am trying to hook into a link in a gridview with jquery but the grid is in an update panel and not visible until the user runs a report. If I add the class ".myLink" to any other "a" tag it works fine, but as the gridview is not there at document.ready I am not sure where to call this from

              $(document).ready(function(){
                $('a .myLink').click(function(){
                  var link = $(this).attr('href');
                  alert(link);
                  return false;
                });
              });

回答1:


You can use .live() to handle events on element created at any time, like this:

$(document).ready(function(){
  $('a .myLink').live('click', function(){
    var link = $(this).attr('href');
    alert(link);
    return false;
  });
});

If you have the container that it'll appear in, and it doesn't get replaced, you can use .delegate() to be more efficient, like this:

$(document).ready(function(){
  $('#containerID').delegate('a .myLink', 'click', function(){
    var link = $(this).attr('href');
    alert(link);
    return false;
  });
});



回答2:


Take a look at jQuery.live().

http://api.jquery.com/live/

$(document).ready(function(){
    $('a .myLink').live('click', function(){
        var link = $(this).attr('href');
        alert(link);
        return false;
    });
});



回答3:


The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation.

Reference



来源:https://stackoverflow.com/questions/4493041/how-to-attach-a-jquery-event-to-a-grid-view-that-is-not-visible-on-document-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!