简体   繁体   中英

Why is this method called multiple times?

When I refresh page, I must click button twice in order to get prompt. After that, each time I click same button and call classicHover() method (without refreshing), i get one plus prompt(two prompts, three prompts, four...).

This is code:

function classicHover(){
    $('#button1').click(function(){
        gridSize = prompt("Set Grid Size")
        $('.container').empty();

        for(i = 0; i < gridSize * gridSize; i++) {
            $('.container').append("<div>a</div>");
        };
    });
};

Button:

<input id="button1" type="button" value="Set New Grid" onclick="classicHover()" />

What am I doing wrong? I am JS/jQuery newbie btw

Your click calls classicHover . classicHover adds a function to the button's listener. Each time you click it, you add something to its listener. So the first click adds 1. The second click runs the 1 and adds another. The third click runs the 2 and adds another. Repeat for each click.

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