[英]jQuery .click() firing ONLY at load
I've searched on here plenty of places and I have not been able to find my situation, so here goes. 我在这里搜索了很多地方,但无法找到我的处境,所以去吧。
I am trying to avoid using the html inline onclick, so in doing so I am using the jquery click() like so 我试图避免使用html内联onclick,因此这样做是在使用jquery click()这样的
$(document).ready(function(){
$("#start").click(game());
});
When I use this, the function game() runs automatically and only runs and load time. 当我使用它时,功能game()自动运行,并且仅运行和加载时间。
If I use the inline onclick, it works only when I click, and it works every time I click. 如果我使用嵌入式onclick,则它仅在单击时有效,并且在每次单击时均有效。 Why is this?
为什么是这样?
Edit.. I swear I tried that.. oh well, It worked!!! 编辑。。我发誓我尝试过。。
You are calling the game()
function and passing its result to .click()
. 您正在调用
game()
函数并将其结果传递给.click()
。 Since its result is (presumably) not a function you have not actually set up a click handler at all. 由于其结果(大概)不是函数,因此您实际上根本没有设置点击处理程序。 You need to pass a reference to the function, so remove the parentheses:
您需要传递对该函数的引用,因此请删除括号:
$("#start").click(game);
You are executing game()
immediately by adding the parenthesis. 您正在通过添加括号立即执行
game()
。 If you want game
to be evaluated on click then you need 如果您想在点击时评估
game
,则需要
$(document).ready(function(){
$("#start").click(game);
});
您需要将其更改为:
$("#start").click(game);
Always more advisable to use .on & an anonymous function since it takes confusions like these out of the picture; 始终建议使用.on和匿名函数,因为这样可以避免此类混乱。
$(document).ready(function() {
$('#start').on('click', function () {
game();
});
}
);
What you're doing would be similar to 您正在做的事情类似于
$(document).ready(function() {
$('#start').on('click', function () {
game();
}());
}
);
Maybe youe need define game this way: 也许您需要这样定义游戏:
var game = function(e,...)
$("#start").click(game);
And remember the first parameter is the event object, passed from click function. 请记住,第一个参数是事件对象,该事件对象是通过click函数传递的。
Regards. 问候。
You could use a jquery function in a html element. 您可以在html元素中使用jquery函数。
<canvas id="game" onclick="jqueryFunction()"></canvas>
In the jqueryFunction() make a if else statement so if game is running : fire. 在jqueryFunction()中执行if else语句,以便在游戏运行时触发:fire。
else if game not running :load game. 否则,如果游戏没有运行:load游戏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.