也许我只是一个 jQuery 菜鸟,但我不明白为什么当我设置一个元素时 .click 事件它会在元素加载时运行。
代码:
//Deal Cards button
$(".draw-cards").click(function(){
var playerId = 1;
var gameId = 20;
$.ajax({
type: 'GET',
url: './system/actions/draw.php',
data: "playerId=" + playerId,
success: function(data) {
//Post to Player Card container
$('#player-cards').html(data);
//Resize Fonts
fontSize();
//For each loaded check if usable
$( ".card" ).each(function() {
var cardId = $(this).attr('id');
comparePlayerCard(cardId, function(data) {
console.log(data);
if (data == 1){
$("#"+cardId+".card").css('box-shadow', '0px 0px 12px 6px #00ff40');
$("#"+cardId+".card").click(addCardToInventory(playerId, gameId, cardId)); // <---- PROBLEM CODE
}
});
});
}
});
});
里面的函数
$("#"+cardId+".card").click(addCardToInventory(playerId, gameId, cardId));
当元素通过 AJAX 加载时正在运行,然后当我单击该元素时它不起作用。不知道为什么。
有什么建议吗?
最佳答案
您不应该以这种方式传递函数调用。
它应该是匿名函数:
$("#"+cardId+".card").click(function() {
functionaddCardToInventory(playerId, gameId, cardId);
});
这通常是最合适的方法,但在循环中使用匿名函数是一种不好的做法。
或者它可以是一个不带参数的函数:
$("#" + cardId + ".card").click(functionaddCardToInventory);
在这种情况下,您可以将您的值描述为全局值或在 data
属性中:
HTML:
<div id="cardId" class="card" data-game-id="7" data-card-id="11"></div>
JS:
var playedId = 14;
function functionaddCardToInventory()
{
var cardId = $(this).data("card-id");
var gameId = $(this).data("game-id");
// and playerId is global
}
// Function without arguments can be passed this way
$("#" + cardId + ".card").click(functionaddCardToInventory);
关于javascript - AJAX jQuery .click 元素在加载时运行函数而不是单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33093543/