2013-03-03 77 views
1

這裏總的noob,試圖有條件地將一些值附加到一個html對象。這是從我發現的示例代碼構建的,所以請親切...在jQuery中附加條件語句append

$.getJSON('url to facebook json feed', function(fbresults){ 
    $.each(fbresults.data, function(){ 
     $('<div></div>') 
     .append('<h1>' + this.from.name + '</h1>') 
     .append('<p>' + this.story + '</p>') 
     $if (typeof this.picture !== "undefined") { 
      .append('<img src="' + this.picture + '">')}; 
     .appendTo('#facebook') 
      }); 
    }); 
+2

來吧,沒有什麼像'$ if' ...嘗試分離每個附加命令,然後添加條件,其中一些。 – roomcays 2013-03-03 22:58:03

回答

1

jQuery只是一個JavaScript庫。你還在使用JavaScript:

$.getJSON('url to facebook json feed', function(fbresults){ 
    $.each(fbresults.data, function(){ 
     var $div = $('<div>'); 

     $('<h1>', {text: this.from.name}).appendTo($div); 
     $('<p>', {text: this.story}).appendTo($div); 

     if (this.picture) { 
      $('<img>', {src: this.picture}).appendTo($div); 
     } 

     $div.appendTo('#facebook'); 
    }); 
}); 
0

嘗試這樣:

$.getJSON('url to facebook json feed', function(fbresults){ 
    $.each(fbresults.data, function(){ 
     var $wrapper = $('<div></div>') 
      .append('<h1>' + this.from.name + '</h1>') 
      .append('<p>' + this.story + '</p>'); 

     if (this.picture) { 
      $wrapper.append('<img src="' + this.picture + '">'); 
     } else { 
      $wrapper.appendTo('#facebook'); 
     } 
    }); 
}); 
2

你不必鏈一起:

$.getJSON('url to facebook json feed', function(fbresults){ 
    $.each(fbresults.data, function(){ 
     var element = $('<div></div>'); 
     element.append('<h1>' + this.from.name + '</h1>'); 
     element.append('<p>' + this.story + '</p>'); 

     if (typeof this.picture !== "undefined") { 
      element.append('<img src="' + this.picture + '">') 
     }; 
     element.appendTo('#facebook'); 
    }); 
}); 

它也被認爲是好的練習建立你想要追加的字符串並追加到$ .each後面

+0

非常感謝,這工作完美!說實話,我不是一個程序員,只是一個設計師。因此,糟糕的代碼。在JavaScript上參加課程的時間我想! – user2129933 2013-03-03 23:19:08

+0

在這種情況下,我會完全推薦http://www.codecademy.com - 我知道有幾個人學會了使用這個頁面進行編碼。他們提供JavaScript和jQuery課程。如果它有助於解決您的問題,請隨時接受答案。 – MOnsDaR 2013-03-04 15:41:44

1

jQuery的append方法接受多個元素,包括null對象像:

$('<div>').append(
    $('<p>').text('First paragraph'), 
    $('<p>').text('Second paragraph'), 
    null, 
    $('<p>').text('Third paragraph') 
); 

這相當於

$('<div>').append(
    $('<p>').text('First paragraph') 
).append(
    $('<p>').text('Second paragraph') 
).append(
    null 
).append(
    $('<p>').text('Third paragraph') 
); 

請注意,一個null對象將簡單地在最後的DOM元素被忽略。

由於這個原因,可以按如下調整您的代碼:

$.getJSON('url to facebook json feed', function(fbresults){ 
    $.each(fbresults.data, function(){ 
     $('<div></div>').append(
      $('<h1>').html(this.from.name), 
      $('<p>').html(this.story), 
      (this.picture) ? 
       $('<img>').attr('src', this.picture) : 
       null 
     ).appendTo('#facebook') 
    }); 
}); 

附加到div第三元件要麼img元件或null取決於this.picture被定義或不是。