Javascript Jquery。单击身体负荷触发
在车身装载时,会触发按钮单击。这种行为是不需要的。是什么导致函数触发Javascript Jquery。单击身体负荷触发,javascript,jquery,onclick,Javascript,Jquery,Onclick,在车身装载时,会触发按钮单击。这种行为是不需要的。是什么导致函数触发 <!doctype html> <html> <head> <body onload="init()"> <div class="btn"><button type="button" class="btn" id="reset" style="font-size:60px;">Reset</button></div>
<!doctype html>
<html>
<head>
<body onload="init()">
<div class="btn"><button type="button" class="btn" id="reset" style="font-size:60px;">Reset</button></div>
<script>
function init() {
$("#reset").click(sendStatus());
}
// FUNCTIONS
function sendStatus (){
console.log("foo");
}
</script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</body>
</html>
重置
函数init(){
$(“#重置”)。单击(sendStatus());
}
//功能
函数sendStatus(){
控制台日志(“foo”);
}
您在init函数中有一个click事件。您正在body标记的onload属性中调用该函数。代码中几乎没有基本问题
$(function() {
function init() {
$("#reset").click(sendStatus);
}
// FUNCTIONS
function sendStatus() {
console.log("foo");
}
init();
});
这是小提琴 这是因为您将函数的结果传递给处理程序,而不是函数的引用。尝试
$(“#重置”)。单击(发送状态)代码>。您还应该将代码放在$(文档).ready(fn)
块中,而不是使用过时的onload
属性。这非常有用-谢谢。