简体   繁体   中英

jquery from external file not loading

So I know this question has been asked many times but I can't seem to get this working, even though it looks correct to me. My jquery functions from an external file aren't loading properly.

My tableMethods.js external file looks like

$(function(){

// Write FITS
function writeFits(){
    var data = $('.sastable').bootstrapTable('getData');
    var name = $('#fitsname').val();
    $.getJSON($SCRIPT_ROOT + '/writeFits', {'data':JSON.stringify(data),'name':name}, 
        function(data){
            $('#fitsout').text(data.result);
        }); 
}

// Delete rows from data table
function deleteRows(){
    var $table = $('.sastable');
    var $delete = $('#delete'); 

    var ids = $.map($table.bootstrapTable('getSelections'), function (row) {
            return row.id
    });

    $table.bootstrapTable('remove', {
            field: 'id',
            values: ids
    });
}

})

My html header looks like

<script type="text/javascript" src="/static/js/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/static/js/bootstrap-table.js"></script>
<script type='text/javascript' src="/static/js/tableMethods.js"></script>

When I check the inspector, it says the file has loaded yet when I click my button that looks like

<button id="delete" class="btn btn-danger" type='button' onClick='deleteRows()'>Delete Rows</button>

I get the error

Uncaught ReferenceError: deleteRows is not defined

This is a scoping problem. You have to move your functions outside of $(function() { ... })

In JavaScript, anything exclusively defined within a function, generally stays within a function:

var x = 3;

(function() {
    var y = 1;
})();

console.log(x); // 3
console.log(y); // error

So if you're defining a function within a function, you can only invoke it from that function you have defined it in. When trying to invoke it from anywhere else, the inner function will seem undefined.

In your case, you can simply remove the wrapper function:

$(function() { // Delete this...

    ...

}); // And this

For more information, read You Don't Know JS: Scope & Closures

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