簡體   English   中英

來自外部文件的jQuery未加載

[英]jquery from external file not loading

因此,我知道這個問題已經被問過很多次了,但是即使對我來說看起來似乎正確,我似乎也無法解決。 我從外部文件獲取的jQuery函數無法正確加載。

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

})

我的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>

當我檢查檢查器時,它說當我單擊如下所示的按鈕時文件已加載

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

我得到錯誤

Uncaught ReferenceError: deleteRows is not defined

這是一個范圍界定問題。 您必須將函數移至$(function() { ... })

在JavaScript中,僅在函數內定義的所有內容通常都存在於函數內:

var x = 3;

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

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

因此,如果要在一個函數中定義一個函數,則只能從定義了它的那個函數中調用它。當嘗試從其他任何地方調用它時,內部函數似乎是未定義的。

就您而言,您只需刪除包裝函數即可:

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

    ...

}); // And this

有關更多信息,請閱讀“ 您不知道JS:范圍和閉包”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM