jQuery对象文字函数声明错误

jQuery Object literal function declaration error

本文关键字:声明 错误 函数 文字 对象 jQuery      更新时间:2023-09-26

我想知道这段代码有什么问题,它抛出一个语法错误:意外令牌" anotherfunction 如果我添加anotherFunction部分。有人能解释一下为什么,JavaScript让我对所有这些不同的调用函数的方式感到困惑。

var ajax = {
        parseJSONP : function(result) {
            console.log(result)
            //iterate each returned item
            $.each(result.items, function(i, row) {
                $('#listview_test').append('<li><a href="#headline"><img src="' + row.volumeInfo.imageLinks.thumbnail + '" class="ui-li-has-thumb"/><h3>' + row.volumeInfo.title + '</h3></a></li>');
            });
            //end iteration of data returned from server and append to the list
            $('#listview_test').listview('refresh');
            // refresh the list-view so new elements are added to the DOM
        }
        //error is here, I just wanted to add another function here to do 
         something
        anotherFuction : function(){
        }
    }
}

您忘记了对象字面量中第一个成员的关闭}之后的,

您需要分隔每个成员,如下所示:

var ajax = {    
        parseJSONP : function(result) {
            $.each(result.items, function(i, row) {
                $('#listview_test').append('<li><a href="#headline"><img src="' + row.volumeInfo.imageLinks.thumbnail + '" class="ui-li-has-thumb"/><h3>' + row.volumeInfo.title + '</h3></a></li>');
            });
            $('#listview_test').listview('refresh');
        },
      // ^ Here   
       anotherFuction : function(){
           // No more syntax errors!
       }   
}

当你使用"对象字面语法"时,例如:

var object = {};

您必须用逗号分隔所有"成员"(变量,函数)(,)。

那么你的代码将变成:

var ajax = {
   parseJSONP: function(result) { /* function body from above */ },
   something,
   anotherFunction: function() {}
}

注意在somethingparseJSONP之后添加了逗号(,)