У меня проблема с моими данными (в формате JSON). Мне удалось просмотреть результаты моей базы данных и правильно отобразить все элементы на странице. Внутри цикла я привязываю обработчик кликов к элементам с именем класса showProduct, который выполняет обратный вызов функции щелчка в зависимости от того, какой элемент нажат.Нужна консультация по содержимому фильтра JSON
По умолчанию в цикле отображаются ВСЕ элементы на странице. Используя этот класс выше (т. Е. showProduct), я хочу, чтобы функция скрывала текущий элемент (т. Е. DIV), отображающий все и фильтруя только содержимое, относящееся к правильному элементу. Другими словами, я просто хочу показать, какой элемент щелкнул по всем элементам страницы, и только показать это. Но для этого элемента необходимо показать правильный вывод (JSON).
Может ли кто-нибудь помочь мне или помочь мне с тем, что я должен попробовать дальше?
Спасибо!
function openNav() {
document.getElementById("productsSideBar").style.width = "250px";
}
function closeNav() {
document.getElementById("productsSideBar").style.width = "0";
}
$(document).ready(function() {
\t
\t 'use strict';
\t
\t $.ajax({
\t \t dataType: "jsonp",
\t \t url: '',
\t \t success: function(json){
\t \t
\t \t //check for window hash and display appropriate product category \t
\t \t var currentHash = window.location.hash;
\t \t switch(currentHash)
\t \t {
\t \t \t case '#tomatoes':
\t \t \t \t displayTomatoes();
\t \t \t \t break;
\t \t \t case '#oliveoil':
\t \t \t \t displayOliveOil();
\t \t \t \t break;
\t \t \t default:
\t \t \t displayAll();
\t \t \t \t break;
\t \t }
\t \t
\t \t //display product category based on click
\t \t $("#tomatoes").click(function(event){
\t \t \t displayTomatoes();
\t \t });
\t \t $("#oliveoil").click(function(event){
\t \t \t displayOliveOil();
\t \t });
\t \t $("#displayall").click(function(event){
\t \t \t displayAll();
\t \t });
\t \t
\t \t //display tomatoes function
\t \t function displayTomatoes() {
\t \t \t var categoryImage = '';
\t \t
\t \t \t $.each(json, function (i, item) {
\t \t \t \t if (item.itemCommodity == "1120" && item.itemBrandLetter == "C") {
\t \t \t \t \t \t categoryImage += '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">' + '<a href="#"' + 'class="showProduct" data-itemname="'+ item.itemName +'">' +
\t \t \t \t \t \t '<img class="img-responsive img-hover productImagesCategory" src="' + item.imageURL + '">' + '<h3>' + item.itemName + '</h3>' + '</a>' + '</div>';
\t \t \t \t }
\t \t \t });
\t \t \t $('#imagesCategoryProducts').hide().html(categoryImage).fadeIn('slow');
\t \t \t
\t \t \t $(".showProduct").click(function(event){
\t \t \t \t
\t \t \t \t $('#productCategories').hide();
\t \t
\t \t \t \t var productTitle;
\t \t \t \t
\t \t \t \t $.each(json, function (i, item) {
\t \t \t \t if ($(this).data('itemname')) {
\t \t \t \t \t productTitle += '<h1>' + item.itemName + '</h1>';
\t \t \t \t }
\t \t \t \t });
\t \t \t \t
\t \t \t \t $('#productSocialShare').show();
\t \t \t \t $('#individualProduct').show();
\t \t \t $('#relatedProducts').show();
\t \t \t \t $('#productTitle').html(productTitle);
\t
\t \t \t });
\t \t \t closeNav();
\t \t }
\t \t
\t \t //display oliveoil function
\t \t function displayOliveOil() {
\t \t \t var categoryImage = '';
\t \t \t var location;
\t \t
\t \t \t $.each(json, function (i, item) {
\t \t \t \t switch(item._id)
\t \t \t \t {
\t \t \t \t \t case '':
\t \t \t \t \t \t location = '';
\t \t \t \t \t \t break;
\t \t \t \t \t default:
\t \t \t \t \t \t location = '';
\t \t \t \t \t \t break;
\t \t \t \t }
\t \t
\t \t \t \t if (item.itemCommodity == "2120" && item.itemBrandLetter == "C") {
\t \t \t \t \t \t categoryImage += '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">' + '<a href="' + location + '">' +
\t \t \t \t \t \t '<img class="img-responsive img-hover productImagesCategory" src="' + item.imageURL + '">' + '<h3>' + item.itemName + '</h3>' + '</a>' + '</div>';
\t \t \t \t }
\t \t \t });
\t \t \t $('#imagesCategoryProducts').hide().html(categoryImage).fadeIn('slow');
\t \t \t closeNav();
\t \t }
\t \t
\t \t //display all products function
\t \t function displayAll() {
\t \t \t var categoryImage = '';
\t \t \t var location;
\t \t
\t \t \t $.each(json, function (i, item) {
\t \t \t \t categoryImage += '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">' + '<a href="' + location + '">' +
\t \t \t \t '<img class="img-responsive img-hover productImagesCategory" src="' + item.imageURL + '">' + '<h3>' + item.itemName + '</h3>' + '</a>' + '</div>';
\t \t \t \t
\t \t \t });
\t \t \t $('#imagesCategoryProducts').hide().html(categoryImage).fadeIn('slow');
\t \t \t closeNav();
\t \t }
\t \t
\t
\t }
});
});
<section>
<div id="productsSideBar" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="#" id="displayall"><h3>View All</h3></a>
<a href="#" id="tomatoes">Tomatoes</a>
<a href="#" id="sauce">Sauce</a>
<a href="#" id="oliveoil">Olive Oil</a>
<a href="#" id="redwinevinegar">Red Wine Vinegar</a>
<a href="#" id="balsamicvinegar">Balsamic Vinegar</a>
<a href="#" id="peppers">Peppers</a>
<a href="#" id="artichokes">Artichokes</a>
<a href="#" id="olives">Olives</a>
<a href="#" id="beans">Beans</a>
<a href="#" id="caperspignolinuts">Capers & Pignoli Nuts</a>
<a href="#" id="specialties">Specialties</a>
<a href="#" id="spices">Spices</a>
<a href="#" id="fish">Fish</a>
<a href="#" id="brothstockssoups">Broth, Stocks & Soups</a>
<a href="#" id="breadcrumbs">Breadcrumbs</a>
<a href="#" id="gratedcheese">Grated Cheese</a>
</div>
</section>
<section id="productCategories">
\t <div class="container-fluid">
\t <div class="row">
<div class="col-lg-12">
\t <br>
<span class="expandSidebar" onclick="openNav()">☰ Categories</span>
</div>
</div>
<div class="row">
<div class="col-lg-12">
\t <div id="imagesCategoryProducts"></div>
</div>
</div>
\t </div>
</section>
@Taplar добавил мой код выше. Я не включил JSON по соображениям безопасности, но вы поняли эту идею. Обратите внимание, что под функцией «display tomatoes» у меня есть функция щелчка .showProduct. То, где я пытаюсь сузить элементы до определенного элемента в зависимости от того, что нажал, но я не знаю, что делать – Tom
, вот где я не уверен, что делать. Я не был уверен, что если мне нужно сделать оператор if, чтобы соответствовать элементу json его идентификатору при щелчке – Tom
, это часть, пытающаяся выяснить. каждый элемент в файле JSON имеет свой собственный идентификатор. im пытается найти способ, как только я нажимаю на элемент, он показывает только содержимое элементов. вы рекомендуете способ, которым я могу связать идентификатор JSON с событием on click? или есть лучший способ? Я действительно ценю вашу помощь. im все еще учеба – Tom