Syntax error jquery

Asked

Viewed 93 times

7

Hello I’m having a problem with the use of this code. I want inside the div with class output to show the following html code, this code is inside a for so I used the append, here is giving syntax error, you could help me?

 $('.output').append('<li class="canal row"><div class="col"><img style="width: 80px; height: 80px;" class="rounded-circle" src="'+data2.logo+'"></div> <div class="col-6"><p class="tituloCanal"><a href="'+data2.url+'" class="linkTitulo">'+data2.display_name+'</a> </p><p class="desc">'+data2.status+'</p> </div>'+
 if(data.stream===null){+'<div class="online col"> <a href="#" class="onlineIcon">on</a> </div>'+} else{'+<div class="online col"> <a href="#" class="onlineIcon">on</a> </div>'+}+'</li>');
  • 1

    You’re trying to concatenate a if in string?

  • Dude, take that off if from within the append. Put that your string within a variable, manipulates it outside and finally adds the variable in the append.

  • That’s right! @Andersoncarloswoss

2 answers

5

You can’t use the if this way, you need a ternary operator.

See the example below. If the condition is true will be concatenated what comes after the ?, otherwise, what comes after :.

Obviously you could organize the code better and treat it outside, by the way, a tip: give a better organized code.

Anyway, the real problem is using this if-else within the concatenation.

(data.stream === null
? '<div class="online col"> <a href="#" class="onlineIcon">on</a> </div>' 
: '<div class="online col"> <a href="#" class="onlineIcon">on</a> </div>' ) 
+ '</li>';

5


You can’t use if/else inside strings concatenation in this way.

Separates the if/Else part and concatenates only the result. Something like this:

var stream = data.stream === null ?
  '<div class="online col"> <a href="#" class="onlineIcon">on</a> </div>' :
  '<div class="online col"> <a href="#" class="onlineIcon">on</a> </div>';

$('.output').append(
  '<li class="canal row"><div class="col"><img style="width: 80px; height: 80px;" class="rounded-circle" src="' +
  data2.logo + '"></div> <div class="col-6"><p class="tituloCanal"><a href="' +
  data2.url + '" class="linkTitulo">' +
  data2.display_name + '</a> </p><p class="desc">' +
  data2.status + '</p> </div>' + 
  stream +
  '</li>'
);
  • 1

    I didn’t know you couldn’t use if and Else in concatenation, I found your solution to put in a variable with a well-organized ternary condition.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.