2013-02-05 43 views
0

尋找解決方案如何檢測li是否有孩子ul或ol我發現jquerys has()這是非常棒的,除了我需要檢測是否只有實際點擊li有一個孩子,而不是任何一個兄弟姐妹。有沒有辦法做到這一點?文檔不包括這一點。JQuery檢查是否點擊li有孩子ol/ul

HTML

<ol> 
    <li><a class="delete-li" href="">Page 1</a></li> 
    <li><a class="delete-li" href="">Page 2</a></li> 
    <li><a class="delete-li" href="">Page 3 has ol</a> 
      <ol> 
       <li><a class="delete-li" href="">Page 4</a></li> 
       <li><a class="delete-li" href="">Page 5</a></li> 
       <li><a class="delete-li" href="">Page 6</a></li> 
      </ol> 
     </li> 
</ol> 

JS

$('.delete-li').live('click', function(event){ 
event.preventDefault(); 
item_id = $(this).attr('rel'); 
clicked = $(this); 
//////////////////// 
    //check if has sub pages 
      if(clicked.has('ol')){ 
       answer = confirm('This will delete all sub pages and content are you sure?'); 
       console.log(answer); 
       if(answer===true){gogogo=true; 
        }else{gogogo=false;} 
         }else{ gogogo=true;} 
     //if yes run AJAX delete 
     if(gogogo===true){ 
     alert('LI REMOVED'); 
} 
//////////////// 

    }); 

結帳的jsfiddle的代碼。

回答

5

has返回一個jQuery對象,它總是true,爲您的處理程序綁定到a元素,你可以使用next方法和length屬性:

if (clicked.next('ol').length) 

注意live方法已過時,你可以使用on方法代替。

$(document).on('click', '.delete-li', function (event) { 
    event.preventDefault(); 
    var gogogo = false, $clicked = $(this), item_id = this.rel; 
    //////////////////// 
    //check if has sub pages 
    if ($clicked.next('ol').length) { 
     gogogo = confirm('This will delete all sub pages and content are you sure?'); 
     // console.log(gogogo); 
    } 

    if (gogogo === true) { 
     alert('LI REMOVED'); 
    } 
}); 

http://jsfiddle.net/jMF42/

+0

感謝您的答案,但它不工作http://jsfiddle.net/ZqzVN/1/也可能你提供的任何瞭解爲什麼。長度是那裏? –

+1

@TommyArnold我已經更新了答案,'length'返回jQuery集合中選定元素的數量,如果所選元素的長度大於0,那麼'if'語句賦值爲true。 – undefined

+0

感謝您的解釋 –

1

您具有約束力單擊處理到a元素。你需要參考li

listItem = $(this).parent('li'); 
//check if has sub pages 
if (listItem.find('ol').length) { 
    ... 
} 

jsfiddle

0

您在<a>標籤調用函數,這可是沒有孩子。如果你想深入,你需要引用他的父母<li>

$('.delete-li').on('click', function (event) { 
    event.preventDefault(); 
    $this = $(this); 
    if ($this.parent('li').children('ol').length) { 
     answer = confirm('This will delete all sub pages and content are you sure?'); 
     alert(answer); 
    } else { 
     alert('dont'); 
    } 
}); 

http://jsfiddle.net/NGmz6/