简体   繁体   中英

jQuery: Why Won't This For Loop Work?

Fairly specific question here. I have the following code:

$(document).ready(function() {
    var cartButArr = document.querySelectorAll(".toCart")

    for(i=0; i<cartButArr.length; i++){
        cartButArr[i].onclick = cartAdd();
    }
});

And later, the called function:

function cartAdd() {
    alert("yo!");
}

However, this for loop, for whatever reason, will not work properly. When I start up the page, I get a series of six alerts in a row, rather than an alert being called whenever I click. What am I doing wrong?

Thanks in advance!

The onclick event should be attached to a function to be called when that event fires

What you are doing is actually calling the function cartAdd and assigning it's value to onclick, which doesn't recognize it's result as a function

Replace your line

cartButArr[i].onclick = cartAdd();

with this one

cartButArr[i].onclick = cartAdd;

A very minor typo is preventing the loop from working. Change

cartButArr[i].onclick = cartAdd();

to

cartButArr[i].onclick = cartAdd;

The reason it does not work is that cartAdd() invokes the cartAdd() function, triggering the alert. You saw the alert multiple times, because the loop called cartAdd() each time. Want you intended to do was assign the function to the callback handler, not invoke the function.

You have

cartButArr[i].onclick = cartAdd();

so instead of assigning a callback function, you're executing it.

Correct syntax would be:

cartButArr[i].onclick = cartAdd;

(no parenthesis after function name).

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