javascript - 为什么我的函数被调用了多次,而我只按了一次调用该函数的按钮?

标签 javascript php html ajax

我有一个程序,可以在按下一个按钮时生成足球比赛。然后灯具就会显示在屏幕上。首先,我需要在刷新页面之前按按钮两次,以便生成并显示灯具。之后,有时当我按下该按钮时,我可以看到生成了多行,这意味着按下按钮时该函数被多次调用,有时它仅被调用一次,而灯具仅生成一次。

fixture.php

$teams = array("FC FCSB", "AFC Astra Giurgiu", "FC Dinamo 1948", "FC Viitorul 2009", "CSM Politehnica Iasi", "Universitatea Craiova", "FC Botosani", "CFR 1907 Cluj");
$fixPair = new Fixture($teams);
$schedule = $fixPair->getSchedule();
$i = 1;
foreach ($schedule as $rounds) {
    echo "<h5> Etapa " . $i . " </h5>";
    foreach ($rounds as $game) {
        echo "{$game[0]} vs {$game[1]}<br>";
    }
    echo "<br>";
    $i++;
}
echo "<hr>";

JQuery
function genereazaEtape() {
            $('.center').click(function(e){
                e.preventDefault();
                var clickBtnValue = $(this).val();
                var ajaxurl = 'fixture.php',
                data =  {'action': clickBtnValue};
                $.post(ajaxurl, data, function (response) {
                    $("#demo1").html(response);
                });
            });
        };

HTML

<button type="submit" class="center" onclick="genereazaEtape()"> Generate Fixtures</button>
    <div id="demo1"></div>

I have recorded this so you can understand better.

最佳答案

每次执行 $('.center').click(... 时(在本例中,当您单击按钮时)都会添加一个事件监听器(而不是替换),因此如果您执行 10 次 $('.center').click(... 您将拥有 10 个监听器。解决方案是仅添加一次监听器。示例:

$('.center').click(function(e){
                console.log("whatever you want")
            });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="center">click here</button>

关于javascript - 为什么我的函数被调用了多次,而我只按了一次调用该函数的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57349422/

相关文章:

javascript - 将 1 添加到 css 选择器

javascript - 在 mongodb 中合并不同的文档

javascript - 跨浏览器 Javascript XML 解析

html - 单击父元素时防止 contenteditable 元素获得焦点

javascript - 页眉或页脚中的 Google 分析?

javascript - JQuery - 我该怎么做才能完成这项工作?

php - 这段更新 Paypal 按钮的代码有什么问题?我得到 "buttontype invalid error"

php - 如何在 PHP 中初始化对象,然后在自动运行的类中创建什么函数?

php - 如何根据用户输入设置 Laravel 数据库连接

html - 在 bootstrap 的 div 中安排 Div