简体   繁体   English

通过按钮onclick调用功能

[英]Call function from button onclick

Can anyone tell me why the console.log function below returns []? 谁能告诉我为什么下面的console.log函数返回[]? 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. 我知道在文档准备功能顶部声明的变量Card对于文​​档准备功能内的所有函数调用都是可见的。 BTY using console.log(Card[0][0]); BTY使用console.log(Card [0] [0]); returns Uncaught TypeError: Cannot read property '0' of undefined 返回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);

});

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. 如果要确保“记录”您的卡,则必须在“ ajax-success”请求中打印该卡。

 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. 为了使Cards可以用于其他功能,建议您创建一个名为Card.js的文件,并将其包含在html中。

Card.js 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": 这样,在程序的另一部分,您可以声明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);

});

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. 您错过了ajax旁边的一个半冒号。

Hope your problem solved :) 希望您的问题得到解决:)

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

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