打开/关闭盒子时遇到问题。场景假设这样的工作:如果打开一个框,当用户点击另一个框时,应该关闭打开的框并单击应该打开的框。当链接(框)打开时,
$(document).ready(onReady);
function onReady(){
$(".glossary").each(init);
}
var init=function(){var rootElement=this;
$("ul li:odd", rootElement).addClass("odd");
$("ul li:even", rootElement).addClass("even");
$(rootElement).delegate("ul li a", "click", function(e){
toggleItem($(this).next("div"), $("ul li div", rootElement));
})
}
var toggleItem =function (item, set){
if ($(item).hasClass("active")){
deactivateItem(item);
}
else{
activateItem(item, set);
}
}
var activateItem = function(item, set){
$(item).slideDown();
$(set).filter(".active").each(deactivateItem);
$(item).addClass("active");
}
var deactivateItem = function (item){
$(item).slideUp();
$(item).removeClass("active");
}
这是一些HTML代码
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="test1.js"></script>
</head>
<body>
<div class="glossary">
<ul>
<li >
<a href="#">Rose</a>
<div class="" style="display: none;">A rose is a woody perennial of the genus Rosa, within the family Rosaceae. There are over 100 species.</div>
</li>
<li >
<a href="#">Camomile</a>
<div class="" style="display: none;">Chamomile or camomile is the common name for several daisy-like plants of the family Asteraceae that are commonly used to make a herb infusion that can help to induce sleep</div>
</li>
<li >
<a href="#">Mentha</a>
<div class="" style="display: none;">Mentha is a genus of plants in the family Lamiaceae (mint family).The species are not clearly distinct and estimates of the number of species varies from 13 to 18.</div>
</li>
<li >
<a href="#">Viola</a>
<div class="" style="display: none; overflow: hidden;">Viola is a genus of flowering plants in the violet family Violaceae. It is the largest genus in the family, containing between 525 and 600 species.</div>
</li>
</ul>
</div>
</body>
</html>
答案 0 :(得分:1)
问题是jQuery对象没有传递给deactivateItem
函数。
jQuery each
通过this
传递jQuery选择。您的函数deactivateItem
期望将jQuery选择作为第一个参数item
传入。 each
中对activateItem
的调用并未考虑到这一点。
这是有问题的一行:
$(set).filter(".active").each(deactivateItem);
您可能希望将其更改为:
$(set).filter(".active").each(function() {
deactivateItem(this);
});