我有这样的结构
<div id="categoryTree">
<ul>
<li id="cat_15"> <a class="hasSubCat" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">North India</a>
<ul>
<li id="cat_17"> <a class="hasSubCat" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">All India</a>
<ul>
<li id="cat_31"> <a class="" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">First Class</a> </li>
<li id="cat_32"> <a class="" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">Luxury Level</a> </li>
<li id="cat_33"> <a class="" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">Oulent Level</a> </li>
</ul>
</li>
</ul>
</li>
<li id="cat_16"> <a class="hasSubCat" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">South India</a> </li>
<li id="cat_37"> <a class="" href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">All India</a> </li>
</ul>
</div>
我想在点击后添加一个选定的类,并将其从其他人中删除
我正在使用以下代码来执行此操作
$('#categoryTree li').on('click',function(){
$('#categoryTree li').removeClass('selected');
$(this).addClass('selected');
});
但每次将课程添加到顶部li.please帮助..... 在此先感谢
答案 0 :(得分:1)
我没有看到#categoryTree的id,所以我们在这里缺少一些信息,但似乎你想要从选定的兄弟姐妹中删除该类。你可以这样做......
$('#categoryTree li').on('click',function(){
$(this).addClass('selected').siblings().removeClass('selected');
});
答案 1 :(得分:0)
这是因为事件传播,子进程中的click事件传播到父元素。您可以通过拨打Event.stopPropagation();
来阻止它$('#categoryTree li').on('click', function (e) {
e.stopPropagation();
$('#categoryTree .selected').removeClass('selected');
$(this).find('a').addClass('selected');
});
答案 2 :(得分:0)
您可以尝试使用e.stopPropagation()
来阻止事件冒泡到父li
。
$('#categoryTree li').on('click',function(e){
e.stopPropagation();
$(this).closest("div").find("li.selected").removeClass("selected");
$(this).addClass('selected');
});