2012-03-17 2 views
1

jQuery 웹 사이트에서 조건을 추가하여이 코드를 수정했습니다. 그러나 결과가 무엇이든, 항상 첫 번째 'if'에 들어갑니다. 내 상태를 어떻게 작동시킬 수 있습니까?

<script> 
/* attach a submit handler to the form */ 
$("#searchForm").submit(function(event) { 

/* stop form from submitting normally */ 
event.preventDefault(); 

/* get some values from elements on the page: */ 
var $form = $(this), 
    term = $form.find('input[name="s"]').val(), 
    url = $form.attr('action'); 

/* Send the data using post and put the results in a div */ 

**//the condition doesn't work here. It always get into the first "if". Why?** 
$.post(url, { s: term }, 
    function(data) { 
     if (var content = $(data).find('#content')) { 
      console.log('One or more results were found'); 
     } else { 
      console.log('no result'); 
     } 
    } 
); 
}); 
</script> 
+0

유효한 html로 모든 ID가 고유해야하므로 '$ (data) .find ('# content ')'를 사용할 필요가 없다는 것을 언급하고 싶습니다. 단지'$ ('# ' content ')' – nathanjosiah

답변

0

사용 $(data).find('#content').length

당신은 당신의 경우 조건 내에서 var content$(data).find('#content')를 할당한다. $(data).find('#content')은 항상 true 인 객체를 반환하므로 항상 if 조건을 충족시킵니다. 당신이) 요소가 내부 데이터가

$(data).find('#content').length 

찾기 (시도

if ($(data).find('#content').length > 0) { 
     // content exist 
} else { 
     // empty 
} 
1

조건에 할당을 지정했기 때문에. 그것은 항상 사실로 반환됩니다. 하지만 그랬다면

if(data!="") 

과 같은 것이 었습니다. 귀하의 경우에는

+0

맞지 않습니다. if (test = false)하면 else 절로 이동합니다. 문제는 find()가 객체를 반환한다는 것입니다. – Steve

+0

예, 맞습니다. 할당 일지라도, if는 할당 된 변수를 조사합니다. 죄송합니다. 그리고 그것을 시도 할 때 if 내부의 "var"가 먼저 오류를 발생시킵니다. 어떻게 그걸 지나쳤 니? –

0

대신

var content = $(data).find('#content') 

사용할 수 있는지 여부를 확인하려면

항상 객체를 반환, 그것은 너무 항상 사실이 될 것입니다. .size()를 수행하면 실제로 아무것도 포함되어 있는지를 알 수 있습니다.