未捕获的ReferenceError:未定义showCategory

时间:2014-11-03 11:38:43

标签: javascript jquery json jquery-mobile

我已经定义了一个名为showCategory的函数。但是,出于某种原因,我的调试器告诉我没有定义show Category。并且不会加载/生成JSON页面。它还说“Uncaught TypeError:无法读取属性'替换'未定义的”

$.ajax({
type: 'GET',
url: 'http://jsonstub.com/bike/1',
contentType: 'application/json',
beforeSend: function (request) {
    request.setRequestHeader('JsonStub-User-Key', '50caee73-c7ed-43b7-912a-7fd6fcdbfd91');
    request.setRequestHeader('JsonStub-Project-Key', '54fb5790-b2cc-432f-88ee-7d3596b700bd');
}
}).done(function showCategory( urlObj, options )
{
    var categoryName = urlObj.hash.replace( /.*category=/, "" ),
    category = categoryData[ categoryName ],    
    pageSelector = urlObj.hash.replace( /\?.*$/, "" );

if ( category ) {
    var $page = $( pageSelector ),
        $header = $page.children( ":jqmData(role=header)" ),
        $content = $page.children( ":jqmData(role=content)" ),
        markup = "<p>" + category.description + "</p><ol>",     
        content = "<p>" + category.content + "</p>",
        image = "<div class='image'><img src='"  + category.picUrl + "'></img></div>" ,
        cItems = category.items,
        numItems = cItems.length;



    for ( var i = 0; i < numItems; i++ ) {
        markup += "<li>" + cItems[i].name + "</li>";
    }
    markup += "</ol>";


    $header.find( "h3" ).html( category.name );
    $content.html( markup + content + image );
    $page.page();
    $content.find( ":jqmData(role=listview)" ).listview();
    options.dataUrl = urlObj.href;
    $.mobile.changePage( $page, options );



}
})


$(document).bind( "pagebeforechange", function( e, data ) {
if ( typeof data.toPage === "string" ) {
    var u = $.mobile.path.parseUrl( data.toPage ),
        re = /^#category-item/;
    if ( u.hash.search(re) !== -1 ) {           
        showCategory( u, data.options );
        e.preventDefault();

    }
}
});

我试过了一些东西,但它不起作用。任何想法都错了吗?

DEMO JSFIDDLE

1 个答案:

答案 0 :(得分:0)

在AJAX请求的showCategory方法之外定义done函数,然后调用它。

 function showCategory(args){
  //stuff
 }
 $.ajax({
  //ajax stuff
 }).done(function(data){showCategory(argsTakenFromData)})

 $(document).bind( "pagebeforechange", function( e, data ) {
     if ( typeof data.toPage === "string" ) {
        var u = $.mobile.path.parseUrl( data.toPage ),
        re = /^#category-item/;
        if ( u.hash.search(re) !== -1 ) {           
        showCategory( u, data.options );
           e.preventDefault();
        }
      }
  });

应该有所帮助。

UPD done函数调用中稍微更改了我的答案。但是你仍然会得到一个错误,因为你忘了定义categoryData数组,或者我没有看到它的声明,所以请在评论中告诉它,所以,试试这个并声明arr并告诉我结果。