Jquery if子句

时间:2009-09-14 23:39:29

标签: javascript jquery

我需要帮助才能使用jquery编写if语句。因此,如果results.d.ProductName为空,则不显示`$(prdHtml).html(html);

$.ajax({
    type: "POST",
    url: "Services.asmx/GetProduct",
    data: '{ "fieldName": "' + id + '"}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
success: function(results) {
        var html = '<h3>' + results.d.ProductName + '<h3>'
                    + '<a href=""' + results.d.Url + '</a>';
        $(prdHtml).html(html);

3 个答案:

答案 0 :(得分:4)

success: function(results) {
        if(results.d.ProductName.length) {
            var html = '<h3>' + results.d.ProductName + '<h3>'
                        + '<a href=""' + results.d.Url + '</a>';

                $(prdHtml).html(html);
        } else {
            $(prdHtml).hide();
        }
}

答案 1 :(得分:1)

尝试:

success: function(results) {
if (results.d.ProductName!="") {
        var html = '<h3>' + results.d.ProductName + '<h3>'
                    + '<a href=""' + results.d.Url + '</a>';
        $(prdHtml).html(html);
}
}

答案 2 :(得分:0)

success: function(results) {
  // should probably test if d exists before testing for productname
  if (typeof(results.d) == "undefined" || typeof(results.d.ProductName ) != "string")
   return;

  ...code
}