admin管理员组文章数量:1406937
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
本文标签: jQuery39s quotonquot and quotoffquot in pure native javascriptStack Overflow
版权声明:本文标题:jQuery's "on" and "off" in pure native javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744967335a2635027.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论