I'm looking for a way to represent the "on" and "off" capabilities of jQuery in pure JavaScript code.
For example:
jQuery("my_selector_here").on("click", function(){
// some code here...
})
Should be represented in the most (total) accurate way, something like:
myobj.fn.on = function(){
// pure javascript code here...
}
Thanks in advance!
I'm looking for a way to represent the "on" and "off" capabilities of jQuery in pure JavaScript code.
For example:
jQuery("my_selector_here").on("click", function(){
// some code here...
})
Should be represented in the most (total) accurate way, something like:
myobj.fn.on = function(){
// pure javascript code here...
}
Thanks in advance!
Share Improve this question asked Nov 13, 2014 at 13:35 TheCuBeManTheCuBeMan 2,4934 gold badges27 silver badges41 bronze badges 6- 2 Have you tried just looking at the jquery.js and doing a find? – C Bauer Commented Nov 13, 2014 at 13:37
-
4
on
is an event listener, so check outAddEventListener
– DannyTheDev Commented Nov 13, 2014 at 13:37 - 1 @Jai i.imgur./OpFcp.jpg – Rory McCrossan Commented Nov 13, 2014 at 13:39
- @TheCuBeMan HaHaHa so you love it satan....;) – Jai Commented Nov 13, 2014 at 13:43
-
@Archer I don't think you can add event listeners to a collection without looping over the elements. And I'd highly remend using
addEventListener
overonclick
. – pawel Commented Nov 13, 2014 at 13:47
1 Answer
Reset to default 6The most native approach is using the DOM's Element.prototype.addEventListener
method. Which looks pretty straight forward like
elem.addEventListener('click', function( event ) {
}, false);
That is, beside some other magic, what jQuery will call underneath. The biggest issue libraries deal with, is that old'ish Internet Explorer had a different syntax for adding events on Elements. Those used the elem.attachEvent
method, which had some slight differences.
Naively spoken, we could just add to the Elements.prototype
. For instance
Element.prototype.on = function( name, callback ) {
this.addEventListener( name, callback, false );
};
..and then we can use it like
document.body.on('click', function() {
// code
});
Ref.: addEventListener
, jQuery .on
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744967336a4603760.html
评论列表(0条)