寻找一个关于如何检测li是否有子ul或ol的解决方案的方法,我发现jquerys has()非常棒,除了我需要检测实际单击的li是否有孩子ol,而不是其兄弟姐妹。有什么办法吗?该文档没有涵盖这一点。

的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以获得代码。

最佳答案

has返回始终为true的jQuery对象,因为处理程序绑定到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/

07-25 22:11