为什么在我只按一次调用该函数的按钮时多次调用该函数?

时间:2019-08-04 19:00:47

标签: 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.

1 个答案:

答案 0 :(得分:1)

每次执行$('.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>