main.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. (async function responseData() {
  2. const response = await fetch('https://jsonplaceholder.typicode.com/users');
  3. const users = await response.json();
  4. const table = document.getElementById("main");
  5. var tr = table.rows;
  6. for (var i = 1; i < tr.length; i++) {
  7. for (var j = 0; j < tr[i].children.length; j++) {
  8. switch (j) {
  9. case 0 : {
  10. tr[i].children[j].innerHTML = users[i].name;
  11. break;
  12. }
  13. case 1: {
  14. tr[i].children[j].innerHTML = users[i].username;
  15. break;
  16. }
  17. case 2 : {
  18. tr[i].children[j].innerHTML = users[i].email;
  19. break;
  20. }
  21. case 3 : {
  22. tr[i].children[j].innerHTML = users[i].website;
  23. break;
  24. }
  25. }
  26. }
  27. }
  28. for (let i = 1; i < tr.length; i++) {
  29. tr[i].addEventListener("click", function () {
  30. const info = document.querySelector(".information");
  31. const values = [];
  32. info.innerHTML = `${getProp(users[i], 3, [])}`;
  33. function getProp(obj, k, values) {
  34. let count = 1;
  35. for(var i in obj) {
  36. if(typeof(obj[i]) === 'object') {
  37. getProp(obj[i], k - 1, values );
  38. } else {
  39. values.push(obj[i]);
  40. if ((k === 1) && (count ===obj[i].length)){
  41. return null;
  42. }
  43. }
  44. count++;
  45. }
  46. return values;
  47. }
  48. info.style.display = "block";
  49. info.addEventListener("click", function () {
  50. info.style.display = "none";
  51. })
  52. })
  53. }
  54. function sortIncrease(e) {
  55. if (e.target.tagName != "TH") return;
  56. const index = e.target.cellIndex;
  57. const tbody = table.getElementsByTagName('tbody')[0];
  58. const rowsArray = [];
  59. for (let i = 0; i < tbody.rows.length; i++) {
  60. rowsArray.push(tbody.rows[i].children[index].innerHTML)
  61. }
  62. rowsArray.sort();
  63. for (let i = 0; i < tbody.rows.length; i++) {
  64. tbody.rows[i].children[index].innerHTML = rowsArray[i];
  65. }
  66. table.removeEventListener("click", sortIncrease)
  67. table.addEventListener("click", sortDecrease);
  68. }
  69. function sortDecrease(e) {
  70. if (e.target.tagName != "TH") return;
  71. const index = e.target.cellIndex;
  72. const tbody = table.getElementsByTagName('tbody')[0];
  73. const rowsArray = [];
  74. for (let i = 0; i < tbody.rows.length; i++) {
  75. rowsArray.push(tbody.rows[i].children[index].innerHTML)
  76. }
  77. rowsArray.reverse();
  78. for (let i = 0; i < tbody.rows.length; i++) {
  79. tbody.rows[i].children[index].innerHTML = rowsArray[i];
  80. }
  81. table.removeEventListener("click", sortDecrease)
  82. table.addEventListener("click", sortIncrease);
  83. }
  84. table.addEventListener("click", sortIncrease)
  85. })();