在a中绑定b,在$(function(){b})调用b,a会默认执行,为啥?

这是HTML代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>引入js</title>
</head>
<body>
<button id="submit">测试按钮</button>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script src="./js/demo.js"></script>
</body>
</html>

这是引入的js文件

<!DOCTYPE html>
$(function(){
    bindMethod();
})

function bindMethod(){
    $('#submit').on('click',alertMag());
}
function alertMag(){
    alert("测试弹窗!");
}

问题描述:

               运行的页面的时候,会自动运行alertMsg()方法,而绑定的bindMethod()的代码无效;求大神解答原因是啥

 

 $('#submit').on('click',alertMag());

要去掉(),你原来的代码是执行alertMag后,将alertMag返回值(没有返回值默认undefined)作为click的事件处理函数,由于是undefined,没处理函数导致点击没反应

 

====》

 $('#submit').on('click',alertMag);

bindMethod();有效啊。你不是已经alert了嘛

bindMethod()不就是要弹出吗。。。。

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632