我检查了 jQuery 文档,根据它我可以做类似的事情:
function notifyme(){
console.log(true)
}
$('button').on('click', notifyme );
这是正确的。但我的代码似乎不起作用。
这是我的代码中的内容。我有一个带有 id myinput
的 div,如下所示:
<div id="myinput">
<input type="checkbox" value="0"/>
</div>
这是我的 jQuery 代码:
$('#myinput input').on(
'change',
My_fn( $(this).prop('checked') )
);
My_fn( theVal ){
if( theVal == true ){
console.log(true)
}
else{
console.log(false)
}
}
即使我尝试:
$('#myinput input').on(
'click',
My_fn( $(this).prop('checked') )
);
我没有收到控制台日志。
有趣的是,如果我将此代码放在脚本的开头:
My_fn( $('#myinput input').prop('checked') )
由于选中了该复选框,我收到了 true
的控制台日志。
为什么click
或change
事件都没有触发My_fn()
函数?
回答 我得到了它。
首先,我在使用 on 时删除了该函数的参数。所以这
My_fn( $(this).prop('checked') )
变为此 My_fn()
。现在使用 .on()
时。我只是写了
$('#myinput input').on(
'click',
My_fn
);
而且它成功了。感谢任何提供帮助的人。
最佳答案
尝试下面的代码。在函数中传递 $(this).prop('checked') 作为参数是错误的。
$('#myinput input').on(
'click',
My_fn
);
My_fn(){
if( $(this).prop('checked')== true ){
console.log(true)
}
else{
console.log(false)
}
}
或者您可以使用 is() 选择器来检查天气复选框是否选中
My_fn(){
if( $(this).is(':checked') == true ){
console.log(true)
}
else{
console.log(false)
}
}
关于javascript - 为什么点击或更改事件都没有触发我的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29056641/