簡體   English   中英

通過按鈕onclick調用功能

[英]Call function from button onclick

誰能告訴我為什么下面的console.log函數返回[]? 我知道在文檔准備功能頂部聲明的變量Card對於文​​檔准備功能內的所有函數調用都是可見的。 BTY使用console.log(Card [0] [0]); 返回Uncaught TypeError:無法讀取未定義的屬性“ 0”

$(document).ready(function(){
    var Cards = new Array;
    var Card = new Array;
    function showEnglish(){

        $.ajax({
        url: 'flashcards.json',
        datatype: 'json',
        type: 'get',
        cache: true,
        success: function(Cards){
            var Card = Cards.slice(index,index +1);
            $("#uktext").text(Card[0][0]);  

            }
        });
        console.log(Card);

});

因為可能是您嘗試打印尚未加載的內容。

如果要確保“記錄”您的卡,則必須在“ ajax-success”請求中打印該卡。

 success: function(Cards){
            var Card = Cards.slice(index,index +1);
            $("#uktext").text(Card[0][0]);  

            }
            console.log(Card);
        })

為了使Cards可以用於其他功能,建議您創建一個名為Card.js的文件,並將其包含在html中。

Card.js

function Card(){
  var Cards = new Array;
  var Card = new Array;

  vat showEnglish = function() {....}

  return {
     getCards: Cards, 
     getCard: Card,
     showEnglish: showEnglish
  };  
};  

這樣,在程序的另一部分,您可以聲明Cards對象並調用其“方法”:

 var c = new Cards();
 c.showEnglish();
$(document).ready(function(){
    var Cards = new Array;
    var Card = new Array;
    function showEnglish(){

        $.ajax({
        url: 'flashcards.json',
        datatype: 'json',
        type: 'get',
        cache: true,
        success: function(Cards){
            var Card = Cards.slice(index,index +1);   // You should not initiate the card inside the function. use card instead of Cards. For success call back some other callback name.
            $("#uktext").text(Card[0][0]);  

            }
        });
}
        console.log(Card);

});

您不應在功能內啟動卡。 使用卡代替卡。 為了成功,請回叫其他回調名稱。

您錯過了ajax旁邊的一個半冒號。

希望您的問題得到解決:)

暫無
暫無

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

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