dimanche 25 mars 2018

JavaScript - Using an if statement to check if a word is in a sentence

So here is my code

$(function() {
$.getJSON('test.json', function(data) {
  var items = [];
  $.each( data.products, function( key, val ) {
  for (var i = 0; i < data.products.length; i++) {
    var obj = data.products[i];
    if (obj.title == 'Hat') {
      var Imgs = '<div class="Hats"><img src="' + obj.imUrl + '"></div>'
      $(Imgs).appendTo($(".HatsImages"));
    }
  }
});})})

So I'm stating if 'obj.title' (which is the sentence 'Plain Black Adjustable Hat') has the word Hat init then append 'obj.imUrl' to my HTML.

If I replace 'Hat' with 'Plain Black Adjustable Hat' it works but I just want to check for the word 'Hat' not the full sentence, hope this makes sense.

Aucun commentaire:

Enregistrer un commentaire