简体   繁体   English

为什么这个方法会被多次调用?

[英]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...).之后,每次我点击同一个按钮并调用classicHover()方法(不刷新),我得到一加提示(两个提示,三个提示,四个...)。

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我是 JS/jQuery 新手顺便说一句

Your click calls classicHover .您的点击会调用classicHover classicHover adds a function to the button's listener. classicHover向按钮的侦听器添加了一个函数。 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.因此,第一次单击会添加 1。第二次单击会运行 1 并添加另一个。 The third click runs the 2 and adds another.第三次单击运行 2 并添加另一个。 Repeat for each click.每次点击重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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