I use ajax to call PHP to replace two lines in my HTML file. The original lines still have the expected jquery click function, but the click function does not appear on the new two lines echo'ed by my php file (I made sure the class name is exactly the same).
I look up on the Event listener on Chrome inspect element feature and yep, the .click function is missing in the new lines.
Here are my codes:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="replacable">
<p class="editable" id="line1">Edit line 1</p>
<p class="editable" id="line2">Edit line 2</p>
</div>
<h4 id="click_to_replace">Click to replace line 1 and 2</h4>
<script>
$('.editable').click(function(){
alert('ID = ' + $(this).attr('id'));
});
$('#click_to_replace').click(function(){
$.ajax({
type: 'POST',
url: "replace.php",
data: {id: $(this).attr('id')},
success: function(newp){
$('#replacable').replaceWith(newp);
}
});
});
</script>
The php file:
<?php
echo '<div id="replacable">
<p class="editable" id="line3">Edit line 3 NEW</p>
<p class="editable" id="line4">Edit line 4 NEW</p></div>'
?>