简体   繁体   English

来自外部文件的jQuery未加载

[英]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. 我从外部文件获取的jQuery函数无法正确加载。

My tableMethods.js external file looks like 我的tableMethods.js外部文件看起来像

$(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 我的html标头看起来像

<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() { ... }) 您必须将函数移至$(function() { ... })

In JavaScript, anything exclusively defined within a function, generally stays within a function: 在JavaScript中,仅在函数内定义的所有内容通常都存在于函数内:

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 有关更多信息,请阅读“ 您不知道JS:范围和闭包”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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