从 onclick 事件调用 jQuery 函数

myn*_*neo 4 javascript jquery

由于一些奇怪的要求以及在我们的应用程序中实现 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>
Run Code Online (Sandbox Code Playgroud)

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);
    });     
});
Run Code Online (Sandbox Code Playgroud)

最后,小提琴链接

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

fro*_*tto 5

使用change事件代替click

$('#chkall').change(function() {
Run Code Online (Sandbox Code Playgroud)

如果仍然没有工作,你可以使用这个:

<input type="checkbox" id="chkall" onclick="myfunc()" />
Run Code Online (Sandbox Code Playgroud)

和:

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);
    }
Run Code Online (Sandbox Code Playgroud)