简体   繁体   中英

Ajax page onclick doesn't work when function defined in $(function(){ })

define two functions like this:

    <script>
        $(function () {
            function testb() {
                alert("ddd");
            }
        })

        function testa() {
            alert("ddd");
        }
    </script>

when page loaded show an ajax page, then call thoese functions from an ajax page, testa will be successful called but not testb .

If your function is inside the document.ready then you will be able to call global functions as well in ajax success. if your ajax call is in global. then you will not be able to call a function inside document.ready. because of scope limitations..

samples: Ajax inside document.ready

 function testb() {
    alert('ddd');
}
$(function () {

    $('[id$=btnsubmit]').on('click', function () {

        $.ajax({
            type: "GET",
            dataType: "json",
            url: "/Content/test",
            success: function (data) {
                // alert(data);
                testa();
                testb();
            }
        });

    });
    function testa() {
        alert('zxfgsfg');
    }
});

it will work..

IF Still you want to call that function in that way, please check below solution:

    function tesss() {
    alert('ddd');
}

var M7 = {};

$('[id$=btnsubmit]').on('click', function () {
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "/Content/test",
        success: function (data) {
            // alert(data);
            M7();
            tesss();
        }
    });

});
$(function () {
    M7 = function () {
        alert('zxfgsfg');
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM