问题
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