从按钮onclick调用功能

时间:2014-07-14 06:58:58

标签: javascript variables console.log

有谁可以告诉我为什么下面的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);

});

2 个答案:

答案 0 :(得分:0)

因为可能,您尝试打印尚未加载的内容。

如果你想确保记录下来'你的卡,你必须在里面打印' ajax-success'请求。

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

            }
            console.log(Card);
        })

为了让卡可用于其他功能,我建议您创建一个名为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对象并调用它的&#34;方法&#34;:

 var c = new Cards();
 c.showEnglish();

答案 1 :(得分: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);   // 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旁边的一个半冒号。

希望你的问题得到解决:)