简体   繁体   中英

How to add if statement in jQuery to check if property exist in JSON file?

I am trying to add an if statement to check if a particular property exist in JSON file, to write the value, if not, do nothing. I want that property if exist to be written in HTML between <div class='titleHolder'> and "<div class='posterHolder'>" Between these two divs i want to have property X, only if exist in JSON file

$( document ).ready( function () {

$.getJSON( "js/appjson.json", function ( data ) {
    for ( var i = 0; i < data.length; i++ ) {
        $( '#jsonLoad' ).append( '<a href="movies.html?id=' + data[ i ].id + '" + <div class="itemsHolder">' +
        "<div class='titleHolder'>" +
        "<h2 >" + data[ i ].name + "</h2>" +
        "</div>"+
        "<div class='posterHolder'>" + data[ i ].posterPath + "</div>" +
        "<div class='summaryShort'>" + data[ i ].summary + "</div>" +
        "<div class='raiting'><p>" + data[ i ].imdb + "</p></div><div class='genderMovie'> " + data[ i ].gender + "</div> " +
        "<div class='directorNdScreen'>" + 'Director by ' + " <p class='director'>" + data[ i ].director + '</p>' + '  ' + ' Screenplay by ' + "<p class='screenplay'>" + data[ i ].screenplay + "</p>" + "</div>"


       + "</a>")

     }
  } )

} );

Break your append part in variables and then concate it. may be that can help ?

 $(document).ready(function() {
 $.getJSON( "js/appjson.json", function(data) {
 for (var i = 0; i < data.length; i++) {
       var content_append = "normal content";
        if(data[i])
        {
          content_append = "content here with data[i]"
        }

          $('#jsonLoad').append(content_append);
       }
     });

});
'<div>' + 
(something === something_else)? 'some data1' : 'some data2' +
'</div>'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM