Pergunta

I have this block :

          return $( "<li></li>" )
              .data( "item.autocomplete", item )
              .append( "<a>" + item.label + "</a>" )
              .appendTo( ul );
        };

And I want to put a ternary in the append statement so that its either just a label or a label with an address

item.address != '' ? item.address : ''

or a little messier but more specific..

if ( item.address != '' )
  "<span class='customer_search_addr'>" + item.address + "</span>"
else
  "<a>" + item.label + "</a>" 

Can I make a chainable proc here since I can't ( I don't think I can ) add this ternary directly within an append statement.

Foi útil?

Solução

Yes, you can add a ternary into the append call:

return $( "<li></li>" )
          .data( "item.autocomplete", item )
          .append( (item.address != '')?("<span class='customer_search_addr'>" + item.address + "</span>"):("<a>" + item.label + "</a>") )
          .appendTo( ul );

Hovewer, it's quite messy, so i would do it like this:

var address = (item.address != '')?
    ("<span class='customer_search_addr'>" + item.address + "</span>"):
    ("<a>" + item.label + "</a>");

 return $( "<li></li>" )
          .data( "item.autocomplete", item )
          .append(address)
          .appendTo( ul );

Outras dicas

It should work.. the argument will be evaluated first and so it would just passing the result to the function.

Proof demo: http://jsfiddle.net/5LpqL/

But I believe it is better if you evaluate it first like below,

var stuffToAppend = (item.address)?"<a>" + item.label + "</a>":"<span class='customer_search_addr'>" + item.address + "</span>";

return $( "<li></li>" )
              .data( "item.autocomplete", item )
              .append( stuffToAppend )
              .appendTo( ul );

Even better is to have the if..else condition..

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top