JSON + jQuery - 过滤问题

时间:2017-01-16 00:53:12

标签: javascript jquery json

我讨厌打扰你们所有人,但我无法让我的过滤器运转起来。我已经在下面发布了我正在处理的代码而没有任何尝试(下拉菜单和复选框没有分配给它们的功能)以使事情更容易看到。

我希望用户能够点击复选框,然后从左侧的下拉菜单中选择国家/地区,以便过滤所有结果。

我希望下拉列表能够自动填充唯一的国家/地区字段(field.COUNTRY)。这是问题中的一个问题 - 我在国家/地区列表上尝试了jQuery.unique和.filter,然后通过jQuery对数据字段结果进行了.filter操作。

基本上,我可能只是太油腻了,看不出我做错了什么,但也许你们其中一个聪明的人可以通过我凌乱的代码看到解决方案。

非常感谢任何帮助!

$(document).ready(function(){
        $.getJSON("https://api.myjson.com/bins/7g9yf.json", function(data){
          
            $.each(data, function(i, field){
              var name = field.NAME;
              var url = field.URL;
              var customs = field.CUSTOMS;
              var ones = field.ONE_OFFS;
              var originals = field.ORIGINAL_MODELS;
              var order = field.ORDER_ONLINE;
              var city = field.CITY;
              var state = field.STATE;
              var country = field.COUNTRY;
              var luthier = field.LUTHIER;
              var email = field.EMAIL;
              var tel = field.TEL;
              var store = field.STORE;
              var info = field.INFO;
              var specialty = field.SPECIALTY;
              var school = field.SCHOOL;
                $("#show-data").append("<div class='LD_item_wrap'>  <div class='LD_1'><h3>" + name + "</h3></div><div class='LD_2'>" + "<a class='LD_lnk' rel='nofollow' href='" + url + "'" + "target='_blank'>" + url + "</a>" + "</div>  <div class='LD_lctn'><div class='LD_7'>" + city + "</div><div class='LD_8'>" + state + "</div><div class='LD_9'>" + country + "</div>  </div><div class='LD_3'>Custom Builds?<span>" + customs + "</span></div><div class='LD_4'>One-Offs?<span>" + ones + "</span></div><div class='LD_5'>Original Models?<span>" + originals + "</span></div><div class='LD_6'>Order Online?<span>" + order + "</span></div>  <div class='LD_cntct_div'>Contact Details</div>  <div class='LD_cnt_cnt'>  <div class='LD_10'><sup>Luthier</sup><span>" + luthier + "</span></div>    <div class='LD_11'><sup>Email</sup><span>" + "<a class='LD_MF' href='mailto:" + email + "' target='_top'>" + email + "</a></span>" + "</div><div class='LD_12'><sup>Tel</sup><span>" + tel + "</span></div> <div class='LD_13'><sup>Shop</sup><span>" + store + "</span></div>  <div class='LD_14'><sup>Info</sup><span>" + info + "</span></div>  <div class='LD_15'><sup>Specialty</sup><span>" + specialty + "</span></div><div class='LD_16'><sup>School/Course</sup><span>" + school + "</span></div></div></div>");
        });
          $('.LD_MF').each(function() {
  var that = $(this);
  that.attr('href', that.attr('href').replace('[x.x]', '.').replace('[x..x]', '@'));
  that.html(that.html().replace('[x.x]', '.').replace('[x..x]', '@'));
});

var check = $('.LD_item_wrap div');
for (var i = 0; i <= check.length; i++) {
       if ($(check[i]).text() == '') {
             $(check[i]).css('display','none');
          }
     }

          
var check3 = $('.LD_item_wrap div span');
var check2 = check3.parent();
for (var i = 0; i <= check3.length; i++) {
       if ($(check3[i]).text() == '') {
             $(check2[i]).css('display','none');
          }
     }

var yn = $('.LD_item_wrap div span');
for (var i = 0; i <= yn.length; i++) {
       if ($(yn[i]).text() == 'Yes') {
             $(yn[i]).html('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 426.667 426.667" style="enable-background:new 0 0 426.667 426.667;" xml:space="preserve" width="15px" height="15px"><g><g><polygon points="293.333,135.04 190.08,240.213 137.173,187.093 108.8,215.467 192.213,298.667 326.187,168.747   " fill="#91DC5A"/></g></g><g><g><path d="M213.333,0C95.513,0,0,95.513,0,213.333s95.513,213.333,213.333,213.333s213.333-95.513,213.333-213.333    S331.154,0,213.333,0z M213.333,388.053c-96.495,0-174.72-78.225-174.72-174.72s78.225-174.72,174.72-174.72    c96.446,0.117,174.602,78.273,174.72,174.72C388.053,309.829,309.829,388.053,213.333,388.053z" fill="#91DC5A"/></g></g></svg>');
          }
     }

for (var i = 0; i <= yn.length; i++) {
       if ($(yn[i]).text() == 'No') {
             $(yn[i]).html('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 426.667 426.667" style="enable-background:new 0 0 426.667 426.667;" xml:space="preserve" width="15px" height="15px"><g><g><polygon points="303.147,153.813 272.853,123.52 213.333,183.253 153.813,123.52 123.52,153.813 183.253,213.333 123.52,272.853     153.813,303.147 213.333,243.413 272.853,303.147 303.147,272.853 243.413,213.333   " fill="#D80027"/></g></g><g><g><path d="M213.333,0C95.513,0,0,95.513,0,213.333s95.513,213.333,213.333,213.333s213.333-95.513,213.333-213.333    S331.154,0,213.333,0z M213.333,388.053c-96.495,0-174.72-78.225-174.72-174.72s78.225-174.72,174.72-174.72    c96.446,0.117,174.602,78.273,174.72,174.72C388.053,309.829,309.829,388.053,213.333,388.053z" fill="#D80027"/></g></g></svg>');
          }
     }

          $('.LD_14').hide();
    });
  
  });
body {margin:0; padding:10px 0;}
/* Testing JSON Data Manipulation */
#LDWrap {border:1px #666 solid; width:600px; height:420px; margin-left:auto; margin-right:auto; padding:0; border-radius:20px; box-shadow:1px 1px 1px #ccc; font-family:Lato; color:#666;}
#LDX {width:600px; height:50px; text-align:center;}
#LDX h2 {font-size:20px; text-transform:uppercase; padding:0; margin:0; line-height:50px;}
#LDX h2 span {color:#cc4c4c;}
#LDMen {width:120px; height:400px; float:left;}
#LDInf {width:480px; height:400px; float:left;}
#LD_scrl {width:100%; text-align:center; line-height:20px;font-size:12px;color:#ccc;}
#LD_filters {font-size:10px;padding:4px;}
#LD_filters select {display:block;padding:0;margin:0 0 10px 0; outline:none;}
#LD_filters span {margin-left:6px;}
#LD_filters > * {display:inline-block;margin:4px 0; line-height:10px;}

#LDMen h4 {color:#cc4c4c;text-align:center;}
#show-data {height:calc(100% - 80px); overflow:scroll; margin:10px; padding:5px; box-shadow:1px 1px 1px #ccc inset;}





.LD_item_wrap a {color:#000;text-decoration:none;}
.LD_item_wrap a:hover {color:#cc4c4c;}
.LD_item_wrap a:active {color:#fff;}
.LD_item_wrap {margin:20px auto; width:calc(100% - 12px); height:auto;border:1px #ccc dotted;padding:5px;}
.LD_item_wrap div {margin:0;padding:0; line-height:20px;}
.LD_item_wrap div span svg {padding-right:10px; float:right;}
.LD_cntct_div {width:100%; border-bottom:1px #ccc dotted;margin:10px 0px 5px 0px !important; color:#ccc; font-size:12px; text-align:center;}
.LD_cnt_cnt {text-align:center;}
.LD_cnt_cnt sup {float:left;font-size:9px;line-height:20px;text-transform:uppercase;}

.LD_1 {text-align:center;}
.LD_1 h3 {font-weight:bold; margin:0; color:#cc4c4c;}
.LD_2 {font-size:12px; text-align:center;}
.LD_lctn {text-align:center; font-size:12px; text-transform:uppercase; margin-bottom:3px !important; font-weight:bold;}
.LD_7 {display:inline-block;}
.LD_7:after {content:'•';padding:0 4px;}
.LD_8 {display:inline-block;}
.LD_8:after {content:'•';padding:0 4px;}
.LD_9 {display:inline-block;}
.LD_3 {}
.LD_4 {}
.LD_5 {}
.LD_6 {}
.LD_10 {}
.LD_11 {font-size:12px;}
.LD_12 {}
.LD_13 {}
.LD_14 {}
.LD_15 {}
.LD_16 {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="LDWrap">
  <div id="LDX"><h2>Custom Guitar Builders <span>Directory</span></h2></div>
  <div id="LDMen">
    <h4>Filter Results</h4>
<div id="LD_filters">
  <span>Country:</span>
  <select>
  <option value="All">All</option>
  <option value="USA">USA</option>
  <option value="Spain">Spain</option>
  <option value="Denmark">Denmark</option>
  <option value="UK">UK</option>
</select>
  <input type="checkbox" name="filt_customs" value="customs"><span>Custom Builders</span><br>
  <input type="checkbox" name="filt_originals" value="originals"><span>Original Models</span><br>
    <input type="checkbox" name="filt_orders" value="orders"><span>Online Orders</span><br>
    </div> <!---filters--->
  </div>
  <div id="LDInf">
    <div id="show-data"></div>
    <div id="LD_scrl">Scroll Down</div>
  </div>
</div>

2 个答案:

答案 0 :(得分:1)

以下是从返回的数据创建唯一国家/地区下拉列表的选项。不是为了有效的方式而是为了完成工作。

$(document).ready(function () {
    var uniqueElements = []

    function CheckIfExists(field) {
        var exists = false;
        $.each(uniqueElements, function (i2, field2) {
            if (field2.COUNTRY == field.COUNTRY) {
                exists = true;
                return true;
            };
        });
        return exists;
    }

    $.getJSON("https://api.myjson.com/bins/7g9yf.json", function (data) {
        $.each(data, function (i, field) {
            if (!CheckIfExists(field)) {
                uniqueElements.push(field)
            }
        });
        $('select').empty();
        $('select').append($('<option>', {
                value : 'All',
                text : 'All'
            }))
        $.each(uniqueElements, function (i, item) {
            $('LD_filters select').append($('<option>', {
                    value : item.COUNTRY,
                    text : item.COUNTRY
                }));
        });

        /*
        Rest of your code
         */

    });

});

答案 1 :(得分:1)

<强>更新

HTML:将此ID添加到这些输入

<select id="countryFilter">
  <option value="All">All</option>
  <option value="USA">USA</option>
  //...
</select>
<input id="customsFilter" type="checkbox" name="filt_customs" value="customs">
<input id="originalsFilter" type="checkbox" name="filt_originals" value="originals">
<input id="orderFilter" type="checkbox" name="filt_orders" value="orders">

Javascript:为上面的输入添加一个事件监听器。在创建类时,将类添加到.LD_item_wrap div以进行过滤。

$(document).ready(function() {
        // Event listenr for the change event on all the input elements.
        $("#countryFilter, #customsFilter, #originalsFilter, #orderFilter").on("change", function() {
            // retrieving their value
            var country = $("#countryFilter").val().toLowerCase();
            var customs = $("#customsFilter").is(":checked");
            var originals = $("#originalsFilter").is(":checked");
            var order = $("#orderFilter").is(":checked");

            // generating a selector that will show only the element matching the criterias chosen by the user
            var selector = "";
            if (country != "all") selector += ".filter-country-" + country;
            if (customs) selector += ".filter-customs";
            if (originals) selector += ".filter-originals";
            if (order) selector += ".filter-order";

            if (selector.length == 0)
                selector = ".LD_item_wrap";
            else
                selector = ".LD_item_wrap" + selector;

            // hide all .LD_item_wrap elements
            $(".LD_item_wrap").hide();
            // and show only the selected ones
            $(selector).show();
        });

        $.getJSON("https://api.myjson.com/bins/7g9yf.json", function(data){

            $.each(data, function(i, field) {
                var name = field.NAME;
                var url = field.URL;
                var customs = field.CUSTOMS;
                var ones = field.ONE_OFFS;
                var originals = field.ORIGINAL_MODELS;
                var order = field.ORDER_ONLINE;
                var city = field.CITY;
                var state = field.STATE;
                var country = field.COUNTRY;
                var luthier = field.LUTHIER;
                var email = field.EMAIL;
                var tel = field.TEL;
                var store = field.STORE;
                var info = field.INFO;
                var specialty = field.SPECIALTY;
                var school = field.SCHOOL;

                // generating the classes that will serve for filtering
                var classString = "filter-country-" + country.toLowerCase();
                if (customs == "Yes") classString += " filter-customs";
                if (originals == "Yes") classString += " filter-originals";
                if (order == "Yes") classString += " filter-order";

                // insert the classString into .LD_item_wrap div's class
                $("#show-data").append("<div class='LD_item_wrap " + classString + "'>  <div class='LD_1'><h3>" + name + "</...

<强>结果:

&#13;
&#13;
$(document).ready(function() {
        $("#countryFilter, #customsFilter, #originalsFilter, #orderFilter").on("change", function() {
            var country = $("#countryFilter").val().toLowerCase();
            var customs = $("#customsFilter").is(":checked");
            var originals = $("#originalsFilter").is(":checked");
            var order = $("#orderFilter").is(":checked");

            var selector = "";
            if (country != "all") selector += ".filter-country-" + country;
            if (customs) selector += ".filter-customs";
            if (originals) selector += ".filter-originals";
            if (order) selector += ".filter-order";

            if (selector.length == 0)
                selector = ".LD_item_wrap";
            else
                selector = ".LD_item_wrap" + selector;

            $(".LD_item_wrap").hide();
            $(selector).show();
        });

        $.getJSON("https://api.myjson.com/bins/7g9yf.json", function(data){

            $.each(data, function(i, field) {
                var name = field.NAME;
                var url = field.URL;
                var customs = field.CUSTOMS;
                var ones = field.ONE_OFFS;
                var originals = field.ORIGINAL_MODELS;
                var order = field.ORDER_ONLINE;
                var city = field.CITY;
                var state = field.STATE;
                var country = field.COUNTRY;
                var luthier = field.LUTHIER;
                var email = field.EMAIL;
                var tel = field.TEL;
                var store = field.STORE;
                var info = field.INFO;
                var specialty = field.SPECIALTY;
                var school = field.SCHOOL;

                var classString = "filter-country-" + country.toLowerCase();
                if (customs == "Yes") classString += " filter-customs";
                if (originals == "Yes") classString += " filter-originals";
                if (order == "Yes") classString += " filter-order";

                $("#show-data").append("<div class='LD_item_wrap " + classString + "'>  <div class='LD_1'><h3>" + name + "</h3></div><div class='LD_2'>" + "<a class='LD_lnk' rel='nofollow' href='" + url + "'" + "target='_blank'>" + url + "</a>" + "</div>  <div class='LD_lctn'><div class='LD_7'>" + city + "</div><div class='LD_8'>" + state + "</div><div class='LD_9'>" + country + "</div>  </div><div class='LD_3'>Custom Builds?<span>" + customs + "</span></div><div class='LD_4'>One-Offs?<span>" + ones + "</span></div><div class='LD_5'>Original Models?<span>" + originals + "</span></div><div class='LD_6'>Order Online?<span>" + order + "</span></div>  <div class='LD_cntct_div'>Contact Details</div>  <div class='LD_cnt_cnt'>  <div class='LD_10'><sup>Luthier</sup><span>" + luthier + "</span></div>    <div class='LD_11'><sup>Email</sup><span>" + "<a class='LD_MF' href='mailto:" + email + "' target='_top'>" + email + "</a></span>" + "</div><div class='LD_12'><sup>Tel</sup><span>" + tel + "</span></div> <div class='LD_13'><sup>Shop</sup><span>" + store + "</span></div>  <div class='LD_14'><sup>Info</sup><span>" + info + "</span></div>  <div class='LD_15'><sup>Specialty</sup><span>" + specialty + "</span></div><div class='LD_16'><sup>School/Course</sup><span>" + school + "</span></div></div></div>");
            });
            $('.LD_MF').each(function() {
                var that = $(this);
                that.attr('href', that.attr('href').replace('[x.x]', '.').replace('[x..x]', '@'));
                that.html(that.html().replace('[x.x]', '.').replace('[x..x]', '@'));
            });

            var check = $('.LD_item_wrap div');
            for (var i = 0; i <= check.length; i++) {
                if ($(check[i]).text() == '') {
                    $(check[i]).css('display', 'none');
                }
            }


            var check3 = $('.LD_item_wrap div span');
            var check2 = check3.parent();
            for (var i = 0; i <= check3.length; i++) {
                if ($(check3[i]).text() == '') {
                    $(check2[i]).css('display', 'none');
                }
            }

            var yn = $('.LD_item_wrap div span');
            for (var i = 0; i <= yn.length; i++) {
                if ($(yn[i]).text() == 'Yes') {
                    $(yn[i]).html('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 426.667 426.667" style="enable-background:new 0 0 426.667 426.667;" xml:space="preserve" width="15px" height="15px"><g><g><polygon points="293.333,135.04 190.08,240.213 137.173,187.093 108.8,215.467 192.213,298.667 326.187,168.747   " fill="#91DC5A"/></g></g><g><g><path d="M213.333,0C95.513,0,0,95.513,0,213.333s95.513,213.333,213.333,213.333s213.333-95.513,213.333-213.333    S331.154,0,213.333,0z M213.333,388.053c-96.495,0-174.72-78.225-174.72-174.72s78.225-174.72,174.72-174.72    c96.446,0.117,174.602,78.273,174.72,174.72C388.053,309.829,309.829,388.053,213.333,388.053z" fill="#91DC5A"/></g></g></svg>');
                }
            }

            for (var i = 0; i <= yn.length; i++) {
                if ($(yn[i]).text() == 'No') {
                    $(yn[i]).html('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 426.667 426.667" style="enable-background:new 0 0 426.667 426.667;" xml:space="preserve" width="15px" height="15px"><g><g><polygon points="303.147,153.813 272.853,123.52 213.333,183.253 153.813,123.52 123.52,153.813 183.253,213.333 123.52,272.853     153.813,303.147 213.333,243.413 272.853,303.147 303.147,272.853 243.413,213.333   " fill="#D80027"/></g></g><g><g><path d="M213.333,0C95.513,0,0,95.513,0,213.333s95.513,213.333,213.333,213.333s213.333-95.513,213.333-213.333    S331.154,0,213.333,0z M213.333,388.053c-96.495,0-174.72-78.225-174.72-174.72s78.225-174.72,174.72-174.72    c96.446,0.117,174.602,78.273,174.72,174.72C388.053,309.829,309.829,388.053,213.333,388.053z" fill="#D80027"/></g></g></svg>');
                }
            }

            $('.LD_14').hide();
        });

    });
&#13;
body {margin:0; padding:10px 0;}
/* Testing JSON Data Manipulation */
#LDWrap {border:1px #666 solid; width:600px; height:420px; margin-left:auto; margin-right:auto; padding:0; border-radius:20px; box-shadow:1px 1px 1px #ccc; font-family:Lato; color:#666;}
#LDX {width:600px; height:50px; text-align:center;}
#LDX h2 {font-size:20px; text-transform:uppercase; padding:0; margin:0; line-height:50px;}
#LDX h2 span {color:#cc4c4c;}
#LDMen {width:120px; height:400px; float:left;}
#LDInf {width:480px; height:400px; float:left;}
#LD_scrl {width:100%; text-align:center; line-height:20px;font-size:12px;color:#ccc;}
#LD_filters {font-size:10px;padding:4px;}
#LD_filters select {display:block;padding:0;margin:0 0 10px 0; outline:none;}
#LD_filters span {margin-left:6px;}
#LD_filters > * {display:inline-block;margin:4px 0; line-height:10px;}

#LDMen h4 {color:#cc4c4c;text-align:center;}
#show-data {height:calc(100% - 80px); overflow:scroll; margin:10px; padding:5px; box-shadow:1px 1px 1px #ccc inset;}





.LD_item_wrap a {color:#000;text-decoration:none;}
.LD_item_wrap a:hover {color:#cc4c4c;}
.LD_item_wrap a:active {color:#fff;}
.LD_item_wrap {margin:20px auto; width:calc(100% - 12px); height:auto;border:1px #ccc dotted;padding:5px;}
.LD_item_wrap div {margin:0;padding:0; line-height:20px;}
.LD_item_wrap div span svg {padding-right:10px; float:right;}
.LD_cntct_div {width:100%; border-bottom:1px #ccc dotted;margin:10px 0px 5px 0px !important; color:#ccc; font-size:12px; text-align:center;}
.LD_cnt_cnt {text-align:center;}
.LD_cnt_cnt sup {float:left;font-size:9px;line-height:20px;text-transform:uppercase;}

.LD_1 {text-align:center;}
.LD_1 h3 {font-weight:bold; margin:0; color:#cc4c4c;}
.LD_2 {font-size:12px; text-align:center;}
.LD_lctn {text-align:center; font-size:12px; text-transform:uppercase; margin-bottom:3px !important; font-weight:bold;}
.LD_7 {display:inline-block;}
.LD_7:after {content:'•';padding:0 4px;}
.LD_8 {display:inline-block;}
.LD_8:after {content:'•';padding:0 4px;}
.LD_9 {display:inline-block;}
.LD_3 {}
.LD_4 {}
.LD_5 {}
.LD_6 {}
.LD_10 {}
.LD_11 {font-size:12px;}
.LD_12 {}
.LD_13 {}
.LD_14 {}
.LD_15 {}
.LD_16 {}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="LDWrap">
  <div id="LDX"><h2>Custom Guitar Builders <span>Directory</span></h2></div>
  <div id="LDMen">
    <h4>Filter Results</h4>
<div id="LD_filters">
  <span>Country:</span>
  <select id="countryFilter">
  <option value="All">All</option>
  <option value="USA">USA</option>
  <option value="Spain">Spain</option>
  <option value="Denmark">Denmark</option>
  <option value="UK">UK</option>
</select>
  <input id="customsFilter" type="checkbox" name="filt_customs" value="customs"><span>Custom Builders</span><br>
  <input id="originalsFilter" type="checkbox" name="filt_originals" value="originals"><span>Original Models</span><br>
    <input id="orderFilter" type="checkbox" name="filt_orders" value="orders"><span>Online Orders</span><br>
    </div> <!---filters--->
  </div>
  <div id="LDInf">
    <div id="show-data"></div>
    <div id="LD_scrl">Scroll Down</div>
  </div>
</div>
&#13;
&#13;
&#13;