.on()
In this chapter you will learn:
on() binds event handlers
.on()
replaces the functionality of all the event methods.
<html> <!-- j a v a 2 s . c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script>
$(function(){
$("#aDiv").on('click', function(){
document.writeln("Handler 1");
});
$("#aDiv").on('click', function(){
document.writeln("Handler 2");
});
});
</script>
</head>
<body>
<div id="aDiv" class="boxDiv">Press Me java2s.com
</div>
</body>
</html>
bind target element with event handler
To use .on()
like
delegate()
or .live()
,
add a second, optional selector argument representing
the target element for the event.
<html> <!-- j a v a 2 s. com-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script>
$(function(){
$(document).on("click", "#anchor", function(event){
document.writeln("I have a handler");
});
$("body").append("<a id='anchor'> I go no where </a>")
});
</script>
</head>
<body>
</body>
</html>
bind events to generic elements
To bind events to generic elements across
the whole page, you use .on()
on
the document and pass in your generic p
or a selector.
Hit Me!
Next chapter...
What you will learn in the next chapter:
- Syntax and Description for .one() event method
- How to bind click event once
- How to execute an event only once
- How to only handler click event once