2017-03-06 43 views
1

我正在處理一個jQuery代碼,它從一個頁面抽取內容並將其顯示在另一個頁面上。用jQuery從另一個頁面抓取一個類的最佳途徑是什麼,但如果這個類不存在,它會尋找另一個類?如果一個類不存在,尋找並抓取另一個類的最佳jQuery方法是什麼?

這裏是什麼,我至今一個精簡版:

<script> 
$("document").ready(function(){ 
    $.get('/blog.html', function(data){ 
     $(data).find("img:nth-of-type(1)").appendTo(".post-image-1"); 
    }); 
}); 
</script> 

換句話說,如果這個代碼不能找到這個頁面上的第一個圖像,讓代碼尋找另一個類。

謝謝!

+0

代碼會有幫助。你有什麼嘗試?澄清你的問題:你是指「從另一個頁面上課獲取什麼?」你是否從現有的DOM對象查詢內容? '$('。classname')'會給你帶給定類的所有元素,如果不存在則給出一個空數組。 –

+0

對不起,@ J.Titus!我已將代碼添加到我的問題中。 – Weebs

+0

在你的示例代碼中,你不是在尋找一個類,而是一個元素的第一個子元素('img')。如果這段代碼沒有找到圖像,那麼它不會找到任何圖像。 – APAD1

回答

0

我相信這就是你要找的。這段代碼檢查jQuery是否找到了圖像。如果是這樣,它將圖像追加到post-image-1元素。如果沒有,您可以搜索其他課程。

<script> 
    $("document").ready(function(){ 
     $.get('/blog.html', function(data){ 
      $data = $(data); 
      $image = $data.find('img:nth-of-type(1)'); 

      if ($image.length > 0) { 
       $image.appendTo('.post-image-1'); 
      } 
      else { 
       // Search for another class here and append it to post-image-1 
       $data.find('.other-class').appendTo('.post-image-1'); 
      } 
     }); 
    }); 
</script> 
相關問題