2014-03-28 51 views
0

的状态中我有这样的jQuery的代码中添加的东西到一个DIV:如何添加附加

$("#destinations ul").append('<li>' + 
      '<h2>' + destination[i].city + '</h2>' + 
      '<p>' + destination[i].desc + 'p>' + 
      '<div class="meta">' + 
      '<span class=meta-date>Added ' + destination[i].added_date + '</span>' + 
      '<span class="meta-comments"><a href="' + destination[i].url + '#reply">' + destination[i].comment_amount + ' comments</a></div>' + 
      '</div></li>'); 

这完美的作品。除非我没有任何评论或日期。然后,我看到与文本“添加”没有日期的div。所以我想把元日期和元注释行作为条件。像:

if (added_date) { 
'<span class=meta-date>Added ' + destination[i].added_date + '</span>' + 
} 

但是,如果我在我的第一个代码中添加,它会给我错误。我能做什么?我应该如何修改我的代码?这很简单,但我现在缺少一些东西,但不知道是什么。脑冻:)

+0

如果可能,请在jsfiddle中发布你的代码。 – iJade

回答

1

试试这个,

var str = '<li><h2>'+destination[i].city+'</h2><p>'+destination[i].desc+'p>'+ 
      '<div class="meta">'; 
if (added_date) { 
    str += '<span class="meta-date">Added '+destination[i].added_date+'</span>'; 
} 
str += '<span class="meta-comments"><a href="'+destination[i].url+'#reply">'+ 
     destination[i].comment_amount+' comments</a></span>' + 
     '</div></li>'; 
$("#destinations ul").append(str); 
0
$("#destinations ul").append('<li>' + 
     '<h2>' + destination[i].city + '</h2>' + 
     '<p>' + destination[i].desc + 'p>' + 
     '<div class="meta">' + 
     (added_date)?'<span class=meta-date>Added ' + destination[i].added_date + '</span>' : '') + 
     '<span class="meta-comments"><a href="' + destination[i].url + '#reply">' + destination[i].comment_amount + ' comments</a></div>' + 
     '</div></li>'); 

如果需要

0

你可以改变 '' 空字符串试试这必将作品...

$(document).ready(function(){ 
    $('#destination ul').append(function(n){ 
     var appendstr = '<li><h2>'+destination[i].city+'</h2><p>'+destination[i].desc+'p>'+ 
     '<div class="meta">'; 
     if (date) { 
      appendstr += '<span class="meta-date">Added '+destination[i].added_date+'</span>'; 
     } 
     appendstr += '<span class="meta-comments"><a href="'+destination[i].url+'#reply">'+ 
    destination[i].comment_amount+' comments</a></span>' + 
    '</div></li>'; 
    return appendstr; 
     }); 
    });