In the console print "aaa", but I can not make it print "bbb" by clicking on click $("#test").
That mistake I'm making? Any suggestions are welcome. Thank you. Sorry for my bad English.
main.js:
$("#load").click(function () {
$.post("second.php",function(data){
$('#result').html(data);
});
return false;
});
main.html:
...
<div id="result"></div>
...
second.php return:
<script>
$(document).ready(function() {
try
{
console.log("aaa");
$("#test").click(function () {
console.log("bbb");
return false;
});
}catch(e){}
});
</script>
<div>hello</div>
<a id="test" href="#">Test</a>
The problem is that document.ready
has already occured in the main page. This means that any code in your AJAX will fire immediately even when wrapped in document.ready
. If the code precedes the html it referrs to, it will fire before the html exists
If you place your code after the same html it will work.
The alternative is to use on()
to delegate event handlers to future elements that don't exist when page loads. Uou can use on()
in the main page and run it when main page loads
Delegation example
$(document).on('click','#test', function(){
console.log('bbbb');
return false;
});