Elements in ajax loaded div not accessible from jQuery
I am using jQuery's $.get() to load some content to a div whose id=results :
$.get('dynamicpage.php',
function(data) {
$('#results').html(data);
});开发者_StackOverflow社区
The returned content has got a select in it :
<select id="myselect"><option value="10">10</option></select>
I have already put a listener for the change on this select :
$('#myselect').change(function() {
alert("changed");
});
However, this alert in the listener never gets fired.
Do I need to do something special to access elements in the loaded div from jQuery ?
Thank you !
The issue is that, at the point you added the change event handler to the select, that select didn't exist (or the one that did exist has since been replaced).
You should use the jQuery live() function instead, which will maintain the event binding even if the element is added later.
Try this:
$.get('dynamicpage.php',
function(data) {
$(data).find('#myselect').change(function() {
alert("changed");
})
.end().appendTo('#results');
});
Here you .find()
the #myselect
and attach the change event.
Or this:
$('#results').delegate('#myselect', 'change', function() {
alert("changed");
});
$.get('dynamicpage.php',
function(data) {
$('#results').append(data);
});
Here you attach a .delegate()
handler to #results
that will listen for the change
event on #myselect
. This is a little more efficient than .live()
.
精彩评论