I tried to use 'on' in my code but failed. The code I tried was this:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function clickHandler(e) {
alert('Click!');
}
$(document).on('ready', function() {
$('#click_me').on('click', clickHandler);
})
</script>
</head>
<body>
<input id="click_me" type="button" value="click me" />
</body>
</html>
Though I can replace this code with the code below. I still wonder why my first code with the event on
didn't work.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function clickHandler(e) {
alert('Click!');
}
$(document).ready(function() {
$('#click_me').click(clickHandler);
})
</script>
</head>
<body>
<input id="click_me" type="button" value="click me" />
</body>
</html>
From the documentation for ready()
, emphasis mine:
There is also
$(document).on("ready", handler)
, deprecated as of jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes ready before this event is attached, the handler will not be executed.