繁体   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