2012-11-21 3 views
0

나는이 블록이 있습니다jQuery를 사용하여 일반적인 체인 가능한 proc을 수행 할 수 있습니까?

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

을 그리고 나는 그것의 단지 label 또는 label with an address

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

또는 약간 지저분하지만 하나 더 구체적인 있도록 append 문에서 원을 넣고 싶다. .

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

나는 (내가 할 수 있다고 생각할 수 없기 때문에) 여기에 체인 가능한 proc을 만들 수 있습니까? append 문 내에서 직접 3 진입니다.

+0

있습니다 .. if..else 조건을하는 것입니다 : http://jsfiddle.net/5LpqL/ –

+1

정말 한 줄에 있어야합니까? 읽을 수있게 만드십시오. – epascarello

답변

2

예, 당신이 append 호출에 원을 추가 할 수 있습니다, 그것은 아주 지저분한의

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, 그래서 난 이런 식으로 할 것 :

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); 
+0

위대한 답변 j0hn. 감사합니다. – Trip

1

그것은 작동합니다 있습니다 .. 인수가 먼저 평가 될 것이므로 결과를 함수로 전달할 것입니다.

증명 데모 : http://jsfiddle.net/5LpqL/

하지만 먼저 아래처럼 평가되는 경우가 더 생각

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); 

더 나은

그것은 작동합니다

관련 문제