In an attempt to write better code and improve how I use jQuery, I recently did the reading. One of the new tips that I learned is to use event delegation with jQuery.
While reading, I discovered two โallegedโ different methods of accessing it. The following are snippets of code to illustrate them.
Assuming I have an HTML block as follows:
<html>
<head>
<title>Test Code</title>
</head>
<body>
<div id="switcher">
<button id="button1">Button 1</button>
<button id="button2">Button 1</button>
<button id="button3">Button 2</button>
<button id="button4">Button 3</button>
<button id="button5">Button 4</button>
<button id="button5">Button 5</button>
<button id="button6">Button 6</button>
<button id="button7">Button 7</button>
<button id="button8">Button 8</button>
<button id="button9">Button 9</button>
</div>
</body>
</html>
In a click, I want:
- Get the identifier of the pressed button (for further manipulations).
- Switch the class to โactiveโ for any of the buttons.
Instead of this:
$('#switcher').find('button').click(function(){
var $element = $(this);
var elementid = this.id;
$element.toggleClass('clicked');
});
I can either do it (method 1)
$('#switcher').click(function(eventName){
if ($(eventName.target).is('button')) {
var $element =$(eventName.target);
var elementid = eventName.target.id;
$element.toggleClass('active');
}
});
Or this (method 2)
$('#switcher').on('click', 'button', function(){
var $element = $(this);
var elementid = this.id;
$element.toggleClass('active');
});
- Are these 2 actually both delegation technologies?
- , ( ) ?
- ?