4

由于一些奇怪的要求和 jQuery 在我们的应用程序中实现的方式,我必须通过复选框 onclick 事件调用 jQuery 函数。

下面是通过 div ID 触发的函数的完美实现。但是,相同的代码在我的应用程序中不起作用。

在我的应用程序中,我使用的是 jQuery 版本 1.7.1。我没有收到任何错误,该功能根本不会触发。我正在使用 Chrome 进行调试。当我尝试在 onclick 中调用它时,它会响应,但会抛出undefined.

HTML

<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);
    });     
});

最后,小提琴链接

http://jsfiddle.net/uxRGB/1/

4

3 回答 3

5

使用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-04T13:38:06.587 回答
1

不确定它是否会导致您面临的问题,但您当前的代码在单击它时会更改“全选”复选框本身,这在某些浏览器上可能会导致意外结果。

首先,将代码更改为:

var opt = $(this).parent().find('input[type=checkbox]').not($(this));

这将影响除被单击的复选框之外的所有复选框。

现在假设您想在单击单独的按钮时运行相同的代码,只需:

$("#btnFoo").click(function() {
    $('#chkall').click();
});

更新了小提琴

于 2013-08-04T13:52:35.693 回答
0

你试过这个吗?

 $('#chkall').trigger('click');

这应该执行附加到复选框的任何处理程序和行为。见:http ://api.jquery.com/trigger/

于 2013-08-04T13:31:25.493 回答