如何修正jQuery $ .post结果条件?

我通过在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>

because you are making an assignment in the condition. it's always returned true. but if it was something like

if(data!="")

then it would be a condition.

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

In your case you are assigning $( data ).find( '#content' ) to var content inside your if condition. $( data ).find( '#content' ) returns an object, which is always true so it always satisfy the if condition.

if you want to check whether an element exist inside data use

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

Instead of

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

try

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

find() always returns an object, so it will always be true. If you do .size() you will see if it actually contains anything.