1

I'm building some html based on JSON data returned from a WebMethod. I need to know how to leave out certain

elements, based on if a particualr value is present or not. I've got this, so far but, i get syntax error within VS

$.each(amlData, function (index, item) {
    $('<div class=message><pre><dl><dt>Matched On:</dt><dd>' + item.ItemType +
    '</dd><dt>Date Listed:</dt><dd>' + item.DateListed +
    '</dd><dt>ID:<dt><dd>' + item.ID +
    '</dd><dt>Percentage:</dt><dd>' + item.PercentageMatch +
    '</dd><dt>List:</dt><dd>' + item.List +
    '</dd>' if(item.Gender != null) { + '<dt>Gender:</dt><dd>' + item.Gender   } +  '</dl></pre></div>').appendTo('div#results');                                  
});
4

4 回答 4

4

if 语句在这种情况下不起作用,但三元运算符将:

'</dd>'  + ((item.Gender != null) ? '<dt>Gender:</dt><dd>' + item.Gender + '</dd>' : '<dd></dd>') + '</dl></pre></div>').appendTo('div#results')
于 2013-07-29T14:27:11.490 回答
2

如果那样的话,你不能使用。但你可以这样做:

'</dd>' + (item.Gender != null ? '<dt>Gender:</dt><dd>'+item.Gender : '')+  '</dl>...
于 2013-07-29T14:26:59.440 回答
1

问题是你有一个 if 语句,它需要一个字符串。尝试:

$.each(amlData, function (index, item) {
                      $('<div class=message><pre><dl><dt>Matched On:</dt><dd>' + item.ItemType +
                          '</dd><dt>Date Listed:</dt><dd>' + item.DateListed +
                          '</dd><dt>ID:<dt><dd>' + item.ID +
                          '</dd><dt>Percentage:</dt><dd>' + item.PercentageMatch +
                          '</dd><dt>List:</dt><dd>' + item.List +
                          '</dd>' + ((item.Gender != null) ? '<dt>Gender:</dt><dd>' + item.Gender : '') +  '</dl></pre></div>').appendTo('div#results');

                  });
于 2013-07-29T14:28:30.883 回答
0

尝试,

    变量结果 = "";
    $.each(amlData, function (index, item) {
        result = "你的初始字符串";
        如果(项目。性别!= null){
            结果 = 结果 + "" + item.Gender; // 根据您的条件附加字符串
         }
     });
    $(result).appendTo('div#results');

于 2013-07-29T14:30:13.403 回答