由于一些奇怪的需求以及在我们的应用程序中实现jQuery的方式,我不得不通过复选框onclick事件调用jQuery函数。
下面是通过div触发的函数的一个非常好的实现。但是,在我的应用程序中,同样的代码不能工作。
在我的应用程序中,我使用的是jQuery版本1.7.1。我没有收到任何错误,函数根本不触发。我用Chrome调试。当我尝试在onclick中调用它时,它会响应,但会抛回undefined。
<div id="dialog-confirm" title="Select Options">
<!--I need to call function in onclick event for checkbox below-->
<input type="checkbox" id="chkall" /> Check/Uncheck
<br /><br />
<input type="checkbox" />Option 1<br />
<input type="checkbox" />Option 2<br />
<input type="checkbox" />Option 3<br />
<input type="checkbox" />Option 4<br />
<input type="checkbox" />Option 5<br />
<input type="checkbox" />Option 6<br />
<input type="checkbox" />Option 7
</div>JS
$(function() {
$( "#dialog-confirm" ).dialog({
resizable: false,
height:350,
modal: true,
buttons: {
"Go": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
$(document).ready(function(){
$('#chkall').click(function() {
// this is the function I need to call
var opt = $(this).parent().find('input[type=checkbox]');
opt.prop('checked', $(this).is(':checked') ? true : false);
});
});最后,Fiddle链接
发布于 2013-08-04 13:38:06
使用change事件而不是click
$('#chkall').change(function() {如果仍未工作,则可以使用以下方法:
<input type="checkbox" id="chkall" onclick="myfunc()" />和:
function myfunc () {
// this is the function I need to call
var opt = $("#chkall").parent().find('input[type=checkbox]');
opt.prop('checked', $("#chkall").is(':checked') ? true : false);
}发布于 2013-08-04 13:52:35
不确定它是否导致了您所面临的问题,但是您当前的代码在单击它时正在更改"check all“复选框,这在某些浏览器上可能会导致意外的结果。
首先,将代码更改为:
var opt = $(this).parent().find('input[type=checkbox]').not($(this));这将影响除被单击的复选框之外的所有复选框。
现在假设您想在单击单独的按钮时运行相同的代码,只需:
$("#btnFoo").click(function() {
$('#chkall').click();
});发布于 2013-08-04 13:31:25
https://stackoverflow.com/questions/18043444
复制相似问题