我有动态创建的 div,其中包含各种文章信息,最重要的是每个 div 的标签的唯一列表。
<div class="resultblock">
<h3 id="sr-title"><a href="/Code/Details/2">Blog Post</a></h3>
<p id="srdescription">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>
Last Updated: 01/01/3001 00:00:00 <span class="resultright">
Author: Kayra</span></p>
<p>
Project: Kayra <span class="resultright">CMS:
Umbraco</span></p>
<p class="tag">
Tags:
<a href="/Code?SearchString=Web%20Forms">Web Forms</a> |
<a href="/Code?SearchString=Blog">Blog</a> </p>
</div>
我还有一个完整的标签列表,这些标签是动态创建的,用作过滤 div 的按钮。我希望他们打开和关闭 div;因此,例如,如果用户单击 Facebook 按钮,则只有 Facebook div 会显示,然后如果用户再次单击 Facebook,它将显示所有 div。我还希望这些按钮可以累积工作,所以如果用户点击 Facebook 和 MVC,它只会显示 Facebook 和 MVC 帖子。
<div id="tagbar">
<input type="submit" value="Facebook" class="button" /> <br />
<input type="submit" value="MVC" class="button" /> <br />
<input type="submit" value="Web Forms" class="button" /> <br />
<input type="submit" value="Blog" class="button" /> <br />
</div>
目前我的 jQuery 代码正在产生一些奇怪的行为。单击一个按钮会使过滤器正常工作,但您不能像以前一样单击它并显示所有帖子。单击多个按钮也可以;有时单击关闭按钮会起作用,但这并不一致,有时需要多次单击才能起作用。
我觉得我的代码逻辑有问题,但找不到任何可以帮助我的在线资源。抱歉,如果我的问题模棱两可,但这是因为我不确定问题出在哪里,因为我才刚刚开始使用 jQuery。
$(document).ready(function () {
var tags = new Array();
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function (from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
$("#tagbar .button").click(function () {
var clickedTag = $(this).val(); //Gets the name of the button clicked
if (tags.indexOf(clickedTag) !== -1) {
tags.remove(tags.indexOf(clickedTag));
console.log("unclick");
}
else {
tags.push(clickedTag);
console.log("click");
}
$(".resultblock").each(function () {
var theBlock = $(this);
i = 0;
$(tags).each(function () {
var targetTags = theBlock.find(".tag a").text();
if (!theBlock.hasClass("show") && targetTags.indexOf(tags[i]) !== -1) {
$(theBlock).show();
$(theBlock).addClass("show");
}
else if (!theBlock.hasClass("show")) {
$(theBlock).hide();
};
console.log(tags[i] + " is comparing to " + targetTags + " and resulting in " + (targetTags.indexOf(tags[i]) !== -1));
i++;
});
if ($(theBlock).hasClass("show")) {
$(theBlock).removeClass("show");
}
});
});
});