Reputation: 4798
I have wasted 1 hour on api.jquery.com and my script to identify the problem but still unable.
Here is my script.js
// DOM ready
$(function(){
// gets categories from server
$.post("category.php", function(data) {
$("#category ul").html(data);
});
// tests click event
$("a").click(function(evt) {
alert("Handler for .click() called.");
evt.preventDefault();
});
});
In index.php there are 4 anchor tags first three loaded from server as you can see in script and the last on is preloaded(static)(not loaded from server). Problem is that I have selected all anchor elements in jQuery selector as you can see in script but my event is only working with the last anchor tag which is pre-loaded. What is wrong ? Why the event is not working with the first three anchor tags ?
Upvotes: 1
Views: 2945
Reputation: 523
$(function(){
// gets categories from server
$.post("category.php", function(data) {
$("#category ul").html(data);
// tests click event
$("a").click(function(evt) {
alert("Handler for .click() called.");
evt.preventDefault();
});
});
});
you have to wait till the ajax post request is ready!
Greetings!
Upvotes: 1
Reputation: 13775
Try:
$(document).on('click', 'a', function (){
//do something
});
This will bind your handler to all anchor tags that currently exist and any that will be added dynamically in the future.
Upvotes: 4
Reputation: 8476
try using on
$('body').on('click', 'a', function(evt) {
alert("Handler for .click() called.");
evt.preventDefault();
});
Upvotes: 5