jQuery$.post结果条件

jQuery $.post result condition

本文关键字:条件 结果 post jQuery      更新时间:2023-09-26

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

因为您在条件中进行赋值。它总是真实的。但如果是

if(data!="")

那么这将是一个条件。

使用$( 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
} 

而不是

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

尝试

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

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