Pregunta

My script below generates a url if the $.post() response has an error. I am trying to use .on() so that I can attach a function to the URL generated, but it does not work. When I add the URL in the DOM (without the $.post) it works like a charm, it just does not want to work if the url is generated within $.post(). Any ideas or solution on how I can get it working?

// Do the database check:
$.post("test.php",{searchFor : search},function(data) {
       if(data.response == true) {
           // DO SOME STUFF
       } else if(data.response == false && data.error == "noDoc") {
           $("#resultsTable").html("<tr><td colspan='6'><p><strong>No user found, <a href='#' class='addDoctor'>Click here</a> to add a doctor.</strong></p></tr>");
       } else {
           $("#resultsTable").html("<tr><td colspan='6'><p><strong>"+data.error+"</strong></p></tr>");
       }
   });
});

$(".addDoctor").on("click",function() {
   alert("test");
    return false;
});
¿Fue útil?

Solución

$('.test') in your code, searches for all elements with a class named "test" in your DOM, and adds a click listener to them. This will only affect the elements that can be found when the call to .on is being executed (i.e. not when the actual click happens).

If you are adding elements with the test class after the call to .on, you will need to call .on for an element that will be the parent of all your .test elements, and that will never be destroyed:

$(document).on('click', '.test', function() {
    alert('test');
});

For optimal performance, select the closest possible parent, so that a smaller part of the DOM has to be searched for eligible elements. The use of document here is not necessarily ideal, but it is the closest I can assume, without knowing your DOM.

Otros consejos

You might be wanting something like:


$(".addDoctor").on("click", function(event){
    alert("test");
});

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top