0

I have an html contains a div element with list,

<div id='tree'>
<ul>
<li id='1' class='folder expand'>1</li>
<li id='2'>2</li>
<li id='3' >3</li>
<li id='4'>4</li>
</ul>
</div>

I need to find

1.If the li element has class 'folder'?

$('#tree li').live('click',function() {
    if($(this).hasClass('folder')){
      if($(this).hasClass('expand')){
        $(this).removeClass('expand').addClass('cl');
        }
      else{
        $(this).removeClass('cl').addClass('expand');
        }
            }
}

This code doesn't work. It always go to the else condition.

2.In the above I want to override the class 'expand' with 'collapse'.How to remove only that name matching class??

4

2 回答 2

1

该代码似乎没有任何问题,它应该按给定的方式工作。但是,如果您只打算切换它们,则不需要查看有哪些类。以上都可以简化为

$('#tree li.folder').live('click',function() {
    $(this).toggleClass("expand cl");
});

此外,由于live已被弃用(实际上在 jQuery 1.9 中完全删除),以上内容应使用以下方式编写on

$('#tree').on('click', 'li.folder', function() {
    $(this).toggleClass("expand cl");
});
于 2013-10-08T19:24:11.887 回答
0

我看不出你的代码有什么问题。您应该将您的“实时”侦听器更改为“开启”,因为“实时”已被弃用。

这是带有警报的决策树的工作版本,可帮助您找到您的位置

$(document).on('click', '#tree li', function(){
    if($(this).hasClass('folder')){
      if($(this).hasClass('expand')){
        $(this).removeClass('expand').addClass('cl');
        alert("i have folder and expand classes");
      }
      else{
        $(this).addClass('expand');
          alert("i have folder, but not expand classes");
      }
    }
    else{
        alert("I have no folder class");
    }
});

在这里提琴

于 2013-10-08T20:01:53.503 回答