【发布时间】:2021-11-26 23:52:38
【问题描述】:
return this.each(function(){
const $gameDiv = $("#rps_game");
let $image1, $image2, $imageCaption, html;
let gameAmount = 0;
setGameStart();
$(this).find("#gameAmount button").click(function(event){
event.preventDefault();
if (parseInt($(this).val()) == 1){
gameAmount = 1;
}else if(parseInt($(this).val()) == 3){
gameAmount = 3;
}else if(parseInt($(this).val()) == 5){
gameAmount = 5;
}
console.log(gameAmount);
setGameProperties();
});
$(this).find("#choices button").click(function(event){
event.preventDefault();
console.log("TEST");
});function setGameProperties(){
$gameDiv.empty();
html = ('<img src="images\\question.png" id="player1" alt="Item 1">\
<img src="images\\question.png" id="player2" alt="Item 2">\
<br>\
<h3 id="score">0 - 0</h3>\
<br>\
<div id="choices">\
<button type="button" id="1" value="1">Rock</button>\
<button type="button" id="2" value="2">Paper</button>\
<button type="button" id="3" value="3">Sissors</button>\
</div>');
$gameDiv.append(html);
$("img").css({
"width": settings.imageWidth,
"height": settings.imageHeight,
"border": settings.imageBorder,
"border-radius": settings.borderRadius
});
$gameDiv.css({
"text-align": "center",
});
};
function setGameStart(){
$gameDiv.empty();
html = ('<div id="gameAmount">\
<button type="button" id="1game" value="1">Best of 1</button>\
<button type="button" id="3game" value="3">Best of 3</button>\
<button type="button" id="5game" value="5">Best of 5</button>\
</div>');
$gameDiv.append(html);
};
})
}}(jQuery))
我无法弄清楚为什么我的第二次点击功能不起作用。如果我将 setGameProperties() 从第一次单击函数移到它的外部,那么我的第二次单击函数可以工作,但它会跳过 setGameStart() 函数并直接转到 setGameProperties()。谁能告诉我为什么我不能在我的点击函数中使用 setGameProperties() 或者我如何重写这段代码来工作?
【问题讨论】:
-
您的问题是
setGameProperties添加了 new 按钮。$("#gameAmount button").click仅适用于它运行时存在的按钮 - 所以 不是 新按钮。使用事件委托$("#rps_game").on("click", "#gameAmount button", function...- 并且仅在您的this.each之外设置一次。