• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

Jak zrobić element składanej listy?

Object Storage Arubacloud
0 głosów
57 wizyt
pytanie zadane 7 kwietnia 2019 w JavaScript przez MikeP Początkujący (310 p.)

Chcę utworzyć rozszerzalny widok listy. W moim przypadku możesz zobaczyć wszystkie wyniki testów uczniów.

Spróbuj wykonać następujące czynności:

 

<!DOCTYPE html>
<html>
<body>

<p>
    <label>Text box</label>
    <input type="Search for names" id="myInput" onkeyup="search()" placeholder="Search for names..">
</p>
<p>
    <label>Tag box</label>
    <input type="Search for tags" id="myInput" onkeyup="searchTag()" placeholder="Search for tags..">
</p>
<div class="box">
    <div class="header-box" id="header-box-2">
        More visible content
        <span class="btn" id="btn-expand-box-2" onclick="swap(this)">Show more...</span>
    </div>
    <div class="expandable hidden" id="expandable-box-2">
        <ul id="txtOut">
            <li>22</li>
            <li>88</li>
            <li>66</li>
            <li id="avg"></li>
        </ul>
    </div>
</div>
<div class="box">
    <div class="header-box" id="header-box-2">
        More visible content
        <span class="btn" id="btn-expand-box-2" onclick="swap(this)">Show more...</span>
    </div>
    <div class="expandable hidden" id="expandable-box-2">
        <ul id="txtOut">
            <li>55</li>
            <li>14</li>
            <li>12</li>
            <li id="avg"></li>
        </ul>
    </div>
</div>


</body>

<script>
fetch( 'https://www.hatchways.io/api/assessment/students' )
  .then( function( response ) {
    return response.json( );
  } )
  .then( function( myJson ) {
    const divOut = document.getElementById( 'txtOut' );
    var allStudents = myJson.students;
    for( let k in allStudents ) {
      let txtOut = '';
      let listItem = document.createElement( 'li' );
      let grades =  `${allStudents[k].grades}`;
      //let sum = values.reduce((previous, current) => current += previous);
      //let avg = sum / values.length;

      // Añadimos el nombre como parte del dataset.
      listItem.dataset.nombre = allStudents[k].firstName.toUpperCase( );

      txtOut += `<b>${allStudents[k].firstName}</b><br />`;
      txtOut += `email: ${allStudents[k].email}<br />`;
      txtOut += `Company: ${allStudents[k].company}<br />`;
      txtOut += `Skill: ${allStudents[k].skill}<br />`;
      //txtOut += `Average: ${avg}<br />`;
      txtOut += `Grades: ${allStudents[k].grades}<br />`;
      txtOut += `<img src="${allStudents[k].pic}"><hr />`;

      listItem.innerHTML = txtOut;
      divOut.appendChild( listItem );
    }
  } );

function search() {
  const prefix = document.getElementById( 'myInput' ).value.toUpperCase( );
  const ul = document.getElementById( 'txtOut' );
  const childs = ul.getElementsByTagName( 'li' );
  var idx = -1, item;

  while( item = childs.item( ++idx ) ) {
//        console.log( typeof( item.dataset.nombre ), item.dataset.nombre );
    item.style.display = item.dataset['nombre'].startsWith( prefix ) ? 'initial' : 
'none';
  }
}

function searchTag() {
  const prefix = document.getElementById( 'myInput' ).value.toUpperCase( );
  const ul = document.getElementById( 'txtOut' );
  const childs = ul.getElementsByTagName( 'li' );
  var idx = -1, item;

  while( item = childs.item( ++idx ) ) {
//        console.log( typeof( item.dataset.nombre ), item.dataset.nombre );
    item.style.display = item.dataset['nombre'].startsWith( prefix ) ? 'initial' : 
'none';
  }
}

function swap(e) {
	// variables
	let sum, avg,li=[];
	// creamos un arreglo text
    let text = ["Show more...", "Hide text..."];
    // validamos que el texto del elemento clickeado sea igual al primer elemento del text
    // si lo es le cambiamos el texto a text[1] o lo cambiamos a text[0] en caso contrario
    e.textContent = text[e.textContent == text[0] ? 1 : 0];
    box = e.parentElement.parentElement.querySelector("#expandable-box-2");

    // con  el metodo toggle agregamos la clase si existe o la ocultamos si no
    box.classList.toggle("hidden");
    // validamos que el campo average alla sido calculado anteriormente
    if(box.querySelector("#avg").innerText !="") return;

    // recorremos todos los li atravez de un forEach 
    box.querySelectorAll("li").forEach((el)=>{
    	// validamos que se pueda comvertir el texto a entero y lo agregamos al arreglo li
    	if(parseInt(el.innerText)) li.push(parseInt(el.innerText));
    });

    // calcular el avg:
    // validamos que existe por lo minimo un elemento en li
    if (li.length){
    	// sumamos todos lo valores de li
	    sum = li.reduce(function(a, b) { return a + b; });
	    // calculamos el avg y con toFixed obtenemos solo 2 decimales
	    avg = (sum / li.length).toFixed(2);
	    // agregar a box el texto);
		box.querySelector("#avg").innerText = `El avg es ${avg}`;
	}
}

</script>
</html>

<head>
<style>
body {
        padding: 5% 8%;
    }
    .header-box {
        border       : 1px solid grey;
        border-radius: 5px;
        padding      : 1em;
    }
    .header-box-active {
        border-bottom-left-radius : 0;
        border-bottom-right-radius: 0;
    }
    .btn {
        background   : lightgrey;
        border-radius: 0 4px 4px 0;
        cursor       : pointer;
        float        : right;
        margin       : -1em;
        padding      : 1rem;
    }
    .box {
        padding      : 2em;
    }
    .expandable {
        border       : 1px solid grey;
        border-radius: 0 0 5px 5px;
        border-top   : 0;
        padding      : 1em;
    }
    .hidden {
        display      : none;
    }
    .btn-contract-active {
        border-bottom-right-radius: 0;
    }
    .visible {
        display      : block;
    }
</style>
</head>

Ale przycisk pojawia się na zewnątrz.

Zaloguj lub zarejestruj się, aby odpowiedzieć na to pytanie.

Podobne pytania

+1 głos
1 odpowiedź 122 wizyt
pytanie zadane 26 sierpnia 2016 w JavaScript przez Wookiee Użytkownik (980 p.)
0 głosów
2 odpowiedzi 184 wizyt
pytanie zadane 27 września 2017 w HTML i CSS przez Bartlomiej Bywalec (2,480 p.)

92,566 zapytań

141,420 odpowiedzi

319,614 komentarzy

61,952 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj.

Akademia Sekuraka

Kolejna edycja największej imprezy hakerskiej w Polsce, czyli Mega Sekurak Hacking Party odbędzie się już 20 maja 2024r. Z tej okazji mamy dla Was kod: pasjamshp - jeżeli wpiszecie go w koszyku, to wówczas otrzymacie 40% zniżki na bilet w wersji standard!

Więcej informacji na temat imprezy znajdziecie tutaj. Dziękujemy ekipie Sekuraka za taką fajną zniżkę dla wszystkich Pasjonatów!

Akademia Sekuraka

Niedawno wystartował dodruk tej świetnej, rozchwytywanej książki (około 940 stron). Mamy dla Was kod: pasja (wpiszcie go w koszyku), dzięki któremu otrzymujemy 10% zniżki - dziękujemy zaprzyjaźnionej ekipie Sekuraka za taki bonus dla Pasjonatów! Książka to pierwszy tom z serii o ITsec, który łagodnie wprowadzi w świat bezpieczeństwa IT każdą osobę - warto, polecamy!

...