2012-08-30 64 views
0

我在這段代碼中遇到了一些麻煩,我想做一個判斷,如果next().children() div沒有長度,那麼做一個ajax要求。但它始終使ajax甚至要求div有內容。我的jQuery代碼有些麻煩

下面是HTML代碼:

<noscript> 
<style> 
.more{display:none;} 
</style> 
</noscript> 
<!-- main content --> 
<p class="click hidden" rel="12345">View more</p> 
<div class="more"> 
    <h5>Relative post</h5> 
    <div class="relative-post"></div> 
    <!-- comment area --> 
</div> 
<!-- main content --> 
<p class="click hidden" rel="23456">View more</p> 
<div class="more"> 
    <h5>Relative post</h5> 
    <div class="relative-post"></div> 
    <!-- comment area --> 
</div> 

這裏是jQuery代碼:

jQuery(document).ready(function(){ 
    $(".click").live('click',function() { 
     if($(this).next('.more').is(':visible')){ 
      $(this).next('.more').css('display','none'); 
     }else{ 
      $(this).next('.more').css('display','block'); 
     } 
     if($(this).next('.more').children('.relative-post:has(*)').length){ 
      }else{ 
      var $this = $(this); 
      var item_id = $this.attr('rel'); 
      $.ajax({ 
       url: "process", 
       dataType: "html", 
       type: 'POST', 
       data: 'post=' + item_id, 
       cache: false, 
       success: function(data){ 
        $this.next('.more').children('.relative-post').html(data); 
       } 
      }); 
        } 
     } 
    }); 
}); 
+0

可以清理你的顯示/隱藏代碼 – BZink

+0

Btw live()方法已棄用。在()上使用。 – Ignas

回答

0

代碼替換

if($(this).next('.more').children('.relative-post:has(*)').length) 

與使用jQuery切換()... http://api.jquery.com/toggle/以下

if($(this).next('.more').children('.relative-post').html()) 
+0

我錯了,或者你的回答不會返回一個布爾值 –

0

嘗試

if($(this).next('.more').children('.relative-post').html().length){

2
$(function() { 
    $(document).on('click', '.click', function() { 
     var next = $(this).next('.more'); 
     next.toggle(!next.is(':visible')); 

     if (next.children('.relative-post:empty').length) { 
      var item_id = $(this).attr('rel'); 
      $.ajax({ 
       url: "process", 
       dataType: "html", 
       type: 'POST', 
       data: {post: item_id}, 
       cache: false, 
       success: function(data) { 
        next.children('.relative-post').html(data); 
       } 
      }); 
     } 
    }); 
});​ 

FIDDLE

+0

你可能想使用'contents'而不是'children'。我雖然上了票。 – adu

+0

'contents'也會得到textnodes,但是我不明白我在這裏如何使用它,因爲':empty'表達式是檢查元素以查看它是否爲空的,並且包含textnode? – adeneo