jQuery $ .post结果条件

时间:2012-03-17 06:40:18

标签: javascript jquery ajax

我已经通过在jQuery网站中添加条件来修改此代码。但无论结果如何,它总是进入第一个“如果”。我怎样才能使我的病情发挥作用?

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

3 个答案:

答案 0 :(得分:1)

因为您正在条件中进行作业。它总是回归真实。但如果它像

那样
if(data!="")
那么这将是一个条件。

答案 1 :(得分:0)

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

在您的情况下,您在if条件中将$( data ).find( '#content' )分配给var content$( data ).find( '#content' )返回一个始终为true的对象,因此始终满足if条件。

如果要检查数据使用中是否存在元素

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

答案 2 :(得分:0)

而不是

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

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

find()总是返回一个对象,所以它总是为真。如果你执行.size(),你会看到它是否真的包含任何内容。