Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

html - using javascript libraries don't work on webpage when loading data from json file

I created a javascript code to create grid and populate it with cards, using data from json file, and load them into a web page. This is the code:

// load data into grid container
const container = document.querySelector(".grid");

// get data from the file, using loadData(), inside it populateContainer
function loadData() {
  const request = new XMLHttpRequest();
  request.open("get", "data.json");
  request.onload = () => {
    try {
      const json = JSON.parse(request.responseText);
      populateContainer(json);
    } catch (e) {
      console.warn("error");
    }
  };

  request.send();
}

function populateContainer(json) {
  while (container.firstChild) {
    container.removeChild(container.firstChild);
  }

  json.forEach((row) => {
    const card = document.createElement("div");
    card.setAttribute("class", `grid-item ${row[7]}`);
    card.setAttribute("data-category", `${row[7]}`);

    // header
    let header = document.createElement("div");
    header.setAttribute("class", "card-header");
    header.innerHTML = `Current = ${row[1]}$ Original Price = ${row[2]}$ / Discount = ${row[3]}%`;
    card.appendChild(header);

    // pic
    let img = document.createElement("img");
    img.setAttribute("class", "card-image");
    img.src = `https://${row[6]}`;
    card.appendChild(img);

    // BODY
    let cardBody = document.createElement("div");
    cardBody.setAttribute("class", "card-content");
    card.appendChild(cardBody);

    // -->Title + link
    let cardTitle = document.createElement("h4");
    cardTitle.setAttribute("class", "card-title");
    cardTitle.innerHTML = `<a href='https://${row[4]}'>${row[0]}</a>`;
    cardBody.appendChild(cardTitle);

    container.appendChild(card);
  });
}

document.addEventListener("DOMContentLoaded", () => {
  loadData();
});

This is the html body (the javascript script is in main.js file):

<body>
    
        <div id="filters" class=".filter-button-group button-group">
            <div class="button All"><a href="#">show all</a></div>
            <div class="button HomeGarden"><a href="#">Home & Garden</a></div>
            <div class="button Electronics"><a href="#">Electronics</a></div>
            <div class="button MomKids"><a href="#">Mom & Kids</a></div>
            <div class="button SportsOutdoor"><a href="#">Sports & Outdoor</a></div>
            <div class="button Accessories"><a href="#">Accessories</a></div>
            <div class="button HealthBeauty"><a href="#">Health & Beauty</a></div>
        </div>

        <div class="grid">            
        </div>
    <script src="main.js"></script>
</body>

The code work well, and it create the grid and elements inside it, but when I want to add a filter for those cards by category, using library like https://listjs.com or https://isotope.metafizzy.co it doesnt work.

How I can apply the filter to my code ?

question from:https://stackoverflow.com/questions/65858125/using-javascript-libraries-dont-work-on-webpage-when-loading-data-from-json-fil

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What issues exactly did occur when trying to filter? Here is a technical cut-through on how to get your script working by the following steps:

  • Include Isotope (as a script-tag,using the download-link)
  • Add "data-filter" attributes in HTML (I added three of them as an example):
    <div class="button Electronics" data-filter="[data-category='Electronics']">
  • Initialize Isotope:
    $grid = new Isotope( '.grid',{
      itemSelector: '.grid-item',
      layoutMode: 'fitRows',
    });
  • Whenever you want to filter, filter. I bound your links to the .arrange-fn using JQuery, but feel free to do it some other way:
    $('#filters').on( 'click', 'div.button', function() {
      var filterValue = $( this ).attr('data-filter');
      $grid.arrange({ filter: filterValue });
    });

Did you get any issues trying to do so? I mocked your JSON since I got no service returning it, but in case it's a timing issue, just put the initialization (see above) right below the container.appendChild(card);, that should make it work.

Feel free to ask if I didn't cover some aspect of your question.

Best wishes


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...