简体   繁体   中英

How can I add handler event into an array

I have a element with an event which will be created 100 times in a for loop.
I wanna save the whole elements in an Array by an push() event and call the Array by another function but a error appears:
Uncaught TypeError: Cannot read property 'getBoundingClientRect' of undefined

My Script:

var P = [];
for (var i = 0; i < 100; i++) {
    P.push($('.way')[i].getBoundingClientRect());
}
console.log(P);

Now I have understand that handler events cannot be included in an Array, but why?

What should i do to save the elements into an array?
Or is there other ways to save my handler event?

As you're already using jQuery, you can use $.each :

var P = [];

$('.way').each(function() {
    P.push(this.getBoundingClientRect());
});

console.log(P);

That way you can leave the count of how many items there are outside your script, should it change in the future.

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