@Kirill-Gorelov
С ума с IT

Как можно улучшить js код?

Парни, привет.
Сравнительно недавно изучаю js. И тут как раз подвернулась возможность попрактиковаться.
Надо написать js код. Сделать спойлер для раскрытия скрытия фотогаллерей. На странице. Но, сама фотогаллерея уже готова и нужно минимально изменить ее код, что бы при этом были скрыты фотографии кроме первой фотогаллереи.
В результате у меня получилось вот это.
joxi.ru/vAWv4YWCbxq92W Это оригинал на сайте.
Я перед фотогаллерей вставил ссылку, Которая и будет скрывать или открывать галлерею.
Что тут можно было изменить, что бы сделать код еще лучше?
Приветствую конструктивную критику
https://jsfiddle.net/gorelov/auykqkx3/

code
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $('.spoiler_links').click(function(){
  $(this).parent().children('div.spoiler_body').toggle('normal');
  return false;
 });
var x = document.getElementsByClassName('spoiler_links');
var xx = document.getElementsByClassName('destination');
var sp = document.getElementsByClassName('spoiler_body');
 console.log(x);
 console.log(xx);
  console.log(sp);
   for (var i=0; i<x.length; i++) {
  // forma2.setAttribute('style', 'display:none;');
    var a = x[i];
    var aa = xx[i];
     var sp_n = sp[i];
     console.log(a);
      console.log(aa);
     var name_id = Math.floor(Math.random() * 100); 
     console.log(name_id);
     console.log(sp_n+"sp");
    if(i != 0){
    sp_n.setAttribute('style', 'display:none;');
    }
     $(a).attr('id', name_id);
     $('#'+name_id).prependTo(aa);

  }
});
</script>

<style type="text/css">
 /*.spoiler_body {display:none;} */
 .spoiler_links {
 cursor:pointer;
  border: 1px solid #333; 
    display: inline-block;
    padding: 5px 15px;
    text-decoration: none; 
    color: #000; 
 }
   .spoiler_links:hover {
    box-shadow: 0 0 5px rgba(0,0,0,0.3); 
    background: linear-gradient(to bottom, #fcfff4, #e9e9ce); 
    color: #a00;
   }
</style>


 <a href="" class="spoiler_links">Спойлер №1 (кликните для показа/скрытия)</a>
<div class="destination">

 <div class="spoiler_body">
  Текст под спойлером<br>
  плавно появляется<br>
  и плавно исчезает<br>
  при клике по спойлеру
 </div>
   </div>

<a href="" class="spoiler_links">Спойлер №2 (кликните для показа/скрытия)</a>
<div class="destination">
 
  
 <div class="spoiler_body">
  А это уже другой спойлер!<br>
  И он тоже работает!
 </div>
  </div>
  
  
  <a href="" class="spoiler_links">Спойлер №2 (кликните для показа/скрытия)</a>
<div class="destination">
 
  
 <div class="spoiler_body">
  А это уже другой спойлер!<br>
  И он тоже работает!
  
  3
 </div>
  </div>


<a href="" class="spoiler_links">Спойлер №2 (кликните для показа/скрытия)</a>
<div class="destination">
 
  
 <div class="spoiler_body">
  А это уже другой спойлер!<br>
  И он тоже работает! 44
 </div>
  </div>
  • Вопрос задан
  • 231 просмотр
Пригласить эксперта
Ответы на вопрос 1
Fzero0
@Fzero0
Вечный студент
Ну, например так?
$(document).ready(function() {
  $('.spoiler_links').click(function() {
    $(this).parent().children('div.spoiler_body').toggle('normal');
    return false;
  });
  var x = document.getElementsByClassName('spoiler_links'),
      xx = document.getElementsByClassName('destination'),
      sp = document.getElementsByClassName('spoiler_body'); 
  $(x).each(function( index ) {
  	if (this) {sp[index].setAttribute('style', 'display:none;');}
 		$(this).attr('id', index);
    $('#' + index).prependTo(xx[index]);
	});
});
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы