简体   繁体   中英

Hide or reveal div according to JSON data id

I would like to know how to add a javascript snippet to my code, to reveal or hide a div according to the category ID my Json returns

<div id="community-members-member-content-categories-container">
  <div class="community-members-member-content-category page-text9">
    Romantic
  </div>
  <div class="community-members-member-content-category page-text9">
    Family
  </div>
  <div class="community-members-member-content-category page-text9">
    Outdoors
    &amp;
    wildlife</div>
  <div class="community-members-member-content-category page-text9">
    Wellness
  </div>
</div>

inside these divs i have my categories

Below I use javascript feth to fetch the information from the server and insert it into the html, but I couldn't find a way to do this with the categories, as it returns a number and not its content!

const baseURL = `http://mulher.store/clara/admin/api/empresa.php?e=8`;
const empresas = document.querySelector('.empresas');
const galeria = document.querySelector('.galeria');

fetch(baseURL).then((answer) => {
  answer.json().then((response) => {
 
    const h1 = document.createElement('h1');
    h1.innerHTML = `
      <span>${response.empresa.nome}</span>                  
    `;
    empresas.append(h1);
 
    const p = document.createElement('p');
    p.innerHTML = `
      <span>${response.empresa.endereco}</span>                  
    `;
    empresas.append(p);

// IMAGES
    response.fotos.map((foto) => {
      const picture = document.createElement('picture');
      picture.innerHTML = `
        <img src="https://remote.la/img/community/${foto.url}" alt="Fotos" />
      `;
      galeria.append(picture);
    });
  });

JSON Results:

object      {5}
empresa     {14}
fotos       [10]
instalacao  [8]
servico     [3]
categoria   [4]
  0 :   1
  1 :   2
  2 :   3
  3 :   5

for example:

category 1: family Category 5: sports this should appear inside the "community-members-member-content-categories-container" divi

Image categories

It's difficult to fully understand your code from the sample.

From what I can understand, you could check the category of the image using a conditional and change the style of the div based on that.

// do this for each label/category
if (response.category.includes(1)) { 
   let div = document.getElementById("family")

   div.style.display = "none"
}

Using the built-in .includes() method, we can check if an array contains a value, or in your case, a number corresponding to a category.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM