繁体   English   中英

jQuery检查单击的li是否有子级ol / ul

[英]JQuery check if clicked li has child ol/ul

寻找关于如何检测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/

您正在将点击处理程序绑定到a元素。 您需要参考li

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

jsfiddle

您正在<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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM