我有一个程序,可以在按下一个按钮时生成足球比赛。然后灯具就会显示在屏幕上。首先,我需要在刷新页面之前按按钮两次,以便生成并显示灯具。之后,有时当我按下该按钮时,我可以看到生成了多行,这意味着按下按钮时该函数被多次调用,有时它仅被调用一次,而灯具仅生成一次。
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>
最佳答案
每次执行 $('.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/