简体   繁体   中英

How to append methods in JavaScript

I'm working with jQuery, making a WordPress website, and ran into issues because Wordpress doesn't seem to work with the $(window).load(...) event listener, due to which I had to change the code.

Here's the original code in jQuery:

$(window).load(function(){
...
}).resize(function() {
...
});

Hers's what I'd changed it to:

window.addEventListener('load', function() {
...
}).resize(function() {
...
});

However, I get an error in console TypeError: windowAddEventListener is undefined . How can I solve this?

You have two issues:

  1. addEventListener return undefined so you can't do anything after it
  2. in vanilla JavaScript there are no resize function this is only in jQuery.

You will need this:

window.addEventListener('load', function() {
...
});

window.addEventListener('resize', function() {
...
});

and if you want chaining you will need:

const x = {
    load: function(fn) {
        window.addEventListener('load', fn);
        return this;
    },
    resize: function(fn) {
        window.addEventListener('resize', fn);
        return this;
    }
};

x.load(function() {

}).resize(function() {

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM