似乎.each函数在内部.each函数中设置变量时,不会正确地循环所有项目,假设这是项目不被删除的原因。 但是我用来测试循环的第二个函数表明它应该可以工作。
有什么特别的意见吗?
HTML代码:
<div id="top-menu">
<ul id="top-menu-main-ul">
<li class="top-menu-main-li">
<a href="#" title="Home">Home</a>
<div class="arrow-bg-above-ul"> </div>
<ul class="top-menu-child-ul">
<li class="top-li-ztyle"><a class="menu-item-2" href="index.php">Admin Home</a></li>
<li><a class="menu-item-2" href="myaccount.php">My Account</a></li>
<li class="bottom-li-ztyle"><a class="menu-item-0" href="logout.php">Logout</a></li>
</ul>
</li>
<li class="top-menu-main-li">
<span class="separator"><a href="#" title="Clients">Clients</a></span>
<div class="arrow-bg-above-ul"> </div>
<ul class="top-menu-child-ul">
<li class="top-li-ztyle"><a class="menu-item-3" href="clients.php">View/Search Clients</a></li>
<li><a class="menu-item-4" href="clientsadd.php">Add New Client</a></li>
<li class="bottom-li-ztyle"><a class="menu-item-5" href="massmail.php">Mass Mail Clients</a></li>
</ul>
</li>
</ul>
</div>
jQuery代码:
var arrayOfitems = ["1","2","33","34","35","36","37","38","39","40","41","42","77"];
$(document).ready(function(){
$(".top-menu-child-ul li a").each(function() {
var thisClass = $(this).attr('class');
var thisClassNum = thisClass.replace('menu-item-', '');
var searchForThisNum = thisClassNum.toString();
if($.inArray(searchForThisNum, arrayOfitems) !== -1 )
{
// do nothing
}
else
{
$("." + thisClass).closest('.li').remove();
}
});
// test that loop should work
var myArray = [];
$(".top-menu-child-ul li a").each(function() {
myArray.push($(this).attr('class'));
});
alert(myArray);
});
小提琴示例: - http://jsfiddle.net/LmUPL/2/
答案 0 :(得分:6)
您正试图找到要移除的class="li"
祖先:
$("." + thisClass).closest('.li').remove();
// -------------------------^
你的意思是说:
$("." + thisClass).closest('li').remove();
找到<li>
。另外,正如评论中Juan Guerrero所述,我想你想这样说:
$(this).closest('li').remove();
确保您准确定位正确的元素。