さまざまな記事情報を含む動的に作成されている 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 コードで奇妙な動作が発生しています。1 つのボタンをクリックするとフィルターが正常に機能しますが、クリックしてすべての投稿を以前のように表示することはできません。複数のボタンをクリックすることもできます。ボタンをクリックしてオフにすると機能する場合もありますが、これは一貫しておらず、機能するまでに複数回クリックする必要がある場合があります。
コードのロジックに問題があるように感じますが、役立つオンライン リソースが見つかりません。私の質問があいまいな場合は申し訳ありませんが、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");
}
});
});
});