2013-02-05 42 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/