【发布时间】:2018-05-30 18:15:25
【问题描述】:
我有想要按数据属性过滤的 div。第一个过滤器是由文本输入过滤的 data-title 属性。我要实现的第二个过滤器是通过 data-tags 属性。数据标签的一个例子是:data-tags="js, php, css"
当用户单击标签按钮时,该标签将添加到标签数组中。我希望能够通过属性、数据标题和数据标签来过滤 div。
这是一个示例 div
<div id="work-card-0" class="work-card col-md-3 text-center" data-title="Test project" data-tags="js,php,css" style=""><img class="work-img img-responsive" src="images/skier.png"><h3 class="work-title">Test project</h3><p class="work-p">This is a sample project</p><a class="btn btn-primary" href="http://google.com" target="_blank">View</a></div>
这里是jquery
$(document).ready(function() {
$.getJSON('work.json', function(data) {
$.each(data, function(key, value) {
$.each(value, function(k, v) {
$("#work-section").append("<div id='work-card-" + v.id + "' class='work-card col-md-3 text-center' data-title='" + v.title + "' data-tags='" + v.tag + "'><img class='work-img img-responsive' src='" + v.image + "'><h3 class='work-title'>" + v.title + "</h3><p class='work-p'>" + v.desc + "</p><a class='btn btn-primary' href='" + v.link + "' target='_blank'>View</a></div>");
});
});
});
$("#filter").on('keyup', function() {
$("#filter-form").submit();
});
var tags = [];
$(".tag").on('click', function() {
var tag = $(this).attr('value');
if (tags.indexOf(tag) == -1) tags.push(tag);
getTags();
});
function getTags() {
$("#tag-holder ul").empty();
for (var i = 0; i < tags.length; i++) {
$("#tag-holder ul").append("<li value='" + i + "'>" + tags[i] + "</li>");
}
}
//remove tags
$("#tag-holder ul").on('click', 'li', function() {
var tag = $(this).attr('value');
tags.splice(tag, 1);
getTags();
});
$("#filter-form").on('submit', function(e) {
e.preventDefault();
getTags();
var search = $("#filter").val();
$.ajax({
url: 'work.html'
}).done(function() {
$(".work-card").hide();
$(".work-card").filter(function() {
return ($(this).data('title').toLowerCase().indexOf(search.toLowerCase()) > -1);
}).filter(function() {
// filter here by tag
}).show();
});
});
$("#reset-btn").on('click', function() {
$("#filter").val("");
tags = [];
getTags();
$(".work-card").show();
});
});
过滤器表单具有标签的输入和所有按钮。当它被提交时,div 被过滤。标题过滤器有效。我如何也可以按数据标签进行过滤。我希望过滤器按两个数据属性进行过滤
【问题讨论】:
标签: jquery