Wednesday 29 June 2016

javascript - JQuery click event does not trigger




I am doing a project and i use ajax to load content into page.



my jquery function is :



function load_room() {
var sem = 0;


$.ajax({
url: 'ajax/room_ajax.php?option=2',
type: 'POST',
data: { 'sem': sem },
dataType: "json",
success: function (data) {
console.log(data[0]);
$("#room").html("");
for (var i = 0; i < data.length; i++) {
var x = i + 1;

$("#room").append("" + x + "" + data[i]['room_name'] + "edit");
};
}
});
}


The content load success fully but when i click on the edit
element it does not trigger the corresponding click event.
The code is like:




$('#edit').on('click', function(){
alert("hai")
});

Answer



You are binding event to element those are present in DOM the time on() is executed. Delegate event to static parent for elements added dynamically.



$('#room').on('click', "#edit", function(){
alert("hai")

});



Delegated events have the advantage that they can process events
from descendant elements that are added to the document at a later
time. By picking an element that is guaranteed to be present at the
time the delegated event handler is attached, you can use delegated
events to avoid the need to frequently attach and remove event
handlers.




No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...