简体   繁体   中英

Call function from button onclick

Can anyone tell me why the console.log function below returns []? I understood that the variable Card declared at the top of the document ready function would be visible to all function calls within the document ready function. BTY using console.log(Card[0][0]); returns Uncaught TypeError: Cannot read property '0' of undefined

$(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);

});

Because probably, you try to print something that is not already loaded.

If you want to be sure to 'log' your card, you have to print it inside 'ajax-success' request.

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

            }
            console.log(Card);
        })

To make Cards available to other functions I suggest you to create a file called, for example, Card.js and include it in html.

Card.js

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

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

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

In this way, in another part of program, you can declare a Cards object and call its "method":

 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);

});

You should not initiate the card inside the function. use card instead of Cards. For success call back some other callback name.

You missed one semi colon next to ajax.

Hope your problem solved :)

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