2014-04-28 30 views
0

下面的代码应该包装图像,但它不,我很难过。难道是因为我用过getJoomndata吗?jquery转换失败低于父级别。为什么?我该怎么办?

<!DOCTYPE html> 
    <html> 
    <head> 
     <title>Working With JSON</title> 
     <style> 
     #content { 
      padding: 5pt; 
      border: 2px dashed lightgray; 
     } 
     </style> 
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
     <script type="text/javascript"> 
      $("document").ready(function() { 
      getJSONData(); 
      addDIV(); 
      jQuery('img', '#content').attr("alt","noddy");   
      }); 

征集图片。

 function getJSONData() { 
     var flickrAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?"; 
     $.getJSON(flickrAPI, { 
       tags: "space needle", 
       tagmode: "any", 
       format: "json" 
       }, 
      successFn); 
      } 

为图像创建HTML。

  function successFn(result) { 
      $.each(result.items, function(i, item) { 
      $("<img>").attr({"src":item.media.m, "alt":"gallery"}).appendTo("#content"); 
      if (i === 4) { 
       return false; 
      } 
      }); 
      } 

下面是对问题的说明。
我可以添加标签到父(div)
但我不能添加标签给孩子。

  function addDIV() { 
      // put each image within it's own div 
      // select all images 
      // this works 
      $('#content').wrap("<DIV></DIV>"); 
      // this doesn't work 
      $('#content img').wrap("<DIV></DIV>"); 
      // Why ??? 
      } 
     </script> 
    </head> 
    <body> 
    <h1>Working With Different Data Types</h1> 
    <div id="content"></div> 
    </body> 
    </html> 

回答

1

您应该运行在回调函数内addDIV功能successFn

function successFn(result) { 
    $.each(result.items, function(i, item) { 
     $("<img>").attr({"src":item.media.m, "alt":"gallery"}).appendTo("#content"); 
     if (i === 4) { 
      return false; 
     } 
    }); 
    addDiv(); 
} 

请记住,您使用的Ajax请求默认情况下是异步的,这意味着JavaScript执行即使回调响应尚未执行,它仍然会继续,在下面的代码中,addDiv()将在回调之前执行successFn()

$("document").ready(function() { 
    getJSONData(); 
    addDIV(); 
    jQuery('img', '#content').attr("alt","noddy");   
});