2016-10-06 3 views
0

Im только начинающий с JQuery. У меня есть короткий сценарий JQuery для генерации некоторых эффектов затухания при запуске события щелчка. Все работает хорошо, но если я хочу использовать несколько разделов с одинаковыми классами, событие click вызывает эффекты в обоих разделах. Поэтому я хочу запустить событие click только в одном разделе за одно время. Какое решение этой проблемы? Должен ли я использовать несколько идентификаторов для каждого раздела?Событие JQuery click с несколькими div с одинаковыми классами

$(document).ready(function(){ 
 
     
 
    $(".button").click(function(){ 
 
     $(".big_img").fadeToggle("slow"); 
 
     $(".bottom_header").fadeToggle("slow"); 
 
     $('.small_img').fadeToggle(); 
 
    }); 
 
    
 
    
 
    $('.button').click(function(e) { 
 
     e.preventDefault; 
 
     if ($(".button").hasClass('button_animate')) { 
 
      $('.button').removeClass('button_animate'); 
 
     } else { 
 
      $('.button').removeClass('button_animate'); 
 
      $(".button").addClass('button_animate'); 
 
     } 
 
    }); 
 
    
 
}); 
 
.client_container { 
 
    position: relative; 
 
    max-width: 300px; 
 
    height: 373px; 
 
    margin-top: 50px; 
 
    background-color: #00ACC1; 
 
    box-shadow: 5px 5px 4px 0px rgba(35, 31, 32, 0.2); 
 
    } 
 
    
 
.button { 
 
    position: absolute; 
 
    right: 20px; 
 
    top: 50px; 
 
    width: 46px; 
 
    height: 46px; 
 
    border-radius: 50%; 
 
    border: none; 
 
    background-color: #00838F; 
 
    box-shadow: 5px 5px 4px 0px rgba(35, 31, 32, 0.2); 
 
    cursor: pointer; 
 
    transition: margin-top .5s ease-in-out; 
 
    } 
 

 
.button_animate { 
 
    margin-top: 228px; 
 
    } 
 
    
 
    .big_img { 
 
    position: absolute; 
 
    top: 0px; 
 
    left: 0px; 
 
    } 
 
    
 
.header{ 
 
    position: absolute; 
 
    margin: 0 auto; 
 
    top: 0; 
 
    left: 0; 
 
    width: 100%; 
 
    height: 76px; 
 
    background-color: #0097A7; 
 
    } 
 

 
    p { 
 
     margin: 47px 0 0 15px; 
 
     } 
 

 
.footer { 
 
    position: absolute; 
 
    bottom: 0; 
 
    left: 0; 
 
    width: 100%; 
 
    height: 73px; 
 
    background-color: #0097A7; 
 
    } 
 
    
 
    p { 
 
     margin: 10px 0 0 12px; 
 
     }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="client_container"> 
 
    <div class="header"></div> 
 
    <div class="footer"></div> 
 
    <img class="big_img" src="http://lorempixel.com/output/people-q-c-300-300-7.jpg"> 
 
    <div class="button button_animate"></div> 
 
</div> 
 

 
<div class="client_container"> 
 
    <div class="header"></div> 
 
    <div class="footer"></div> 
 
    <img class="big_img" src="http://lorempixel.com/output/people-q-c-300-300-7.jpg"> 
 
    <div class="button button_animate"></div> 
 
</div>

+2

Использование DOM навигации и выбор относительно '$ (это)' стрелять эффекты только в разделе, содержащем щелкнул DIV. – Barmar

+2

Это должно быть объяснено в учебниках jQuery. Я не понимаю, почему у нас так много вопросов. – Barmar

+2

И, должно быть, сотню обманов – j08691

ответ

1

Ваша вторая функция щелчок может быть сведена к jQuery toggleclass и эта функция может быть вставлена ​​непосредственно в первый обработчик событий.

Для «bottom_header» и «small_img» в вашем фрагменте нет элемента с этими классами, поэтому я прокомментировал эти строки.

Поэтому код может быть:

$(".button").click(function(e){ 
      e.preventDefault; 
      $(this).toggleClass('button_animate'); 
      $(this).prev(".big_img").fadeToggle("slow"); 
      //$(".bottom_header").fadeToggle("slow"); 
      //$('.small_img').fadeToggle(); 
    }); 

Чтобы получить доступ к "big_img" Я использовал jQuery prev.

Сниппет:

$(document).ready(function(){ 
 
    $(".button").click(function(e){ 
 
    e.preventDefault; 
 
    $(this).toggleClass('button_animate'); 
 
    $(this).prev(".big_img").fadeToggle("slow"); 
 
    //$(".bottom_header").fadeToggle("slow"); 
 
    //$('.small_img').fadeToggle(); 
 
    }); 
 
});
.client_container { 
 
    position: relative; 
 
    max-width: 300px; 
 
    height: 373px; 
 
    margin-top: 50px; 
 
    background-color: #00ACC1; 
 
    box-shadow: 5px 5px 4px 0px rgba(35, 31, 32, 0.2); 
 
} 
 

 
.button { 
 
    position: absolute; 
 
    right: 20px; 
 
    top: 50px; 
 
    width: 46px; 
 
    height: 46px; 
 
    border-radius: 50%; 
 
    border: none; 
 
    background-color: #00838F; 
 
    box-shadow: 5px 5px 4px 0px rgba(35, 31, 32, 0.2); 
 
    cursor: pointer; 
 
    transition: margin-top .5s ease-in-out; 
 
} 
 

 
.button_animate { 
 
    margin-top: 228px; 
 
} 
 

 
.big_img { 
 
    position: absolute; 
 
    top: 0px; 
 
    left: 0px; 
 
} 
 

 
.header{ 
 
    position: absolute; 
 
    margin: 0 auto; 
 
    top: 0; 
 
    left: 0; 
 
    width: 100%; 
 
    height: 76px; 
 
    background-color: #0097A7; 
 
} 
 

 
p { 
 
    margin: 47px 0 0 15px; 
 
} 
 

 
.footer { 
 
    position: absolute; 
 
    bottom: 0; 
 
    left: 0; 
 
    width: 100%; 
 
    height: 73px; 
 
    background-color: #0097A7; 
 
} 
 

 
p { 
 
    margin: 10px 0 0 12px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<div class="client_container"> 
 
    <div class="header"></div> 
 
    <div class="footer"></div> 
 
    <img class="big_img" src="http://lorempixel.com/output/people-q-c-300-300-7.jpg"> 
 
    <div class="button button_animate"></div> 
 
</div> 
 

 
<div class="client_container"> 
 
    <div class="header"></div> 
 
    <div class="footer"></div> 
 
    <img class="big_img" src="http://lorempixel.com/output/people-q-c-300-300-7.jpg"> 
 
    <div class="button button_animate"></div> 
 
</div>

-1

Это имело бы смысл, чтобы изменить имя класса второго изображения, просто скопировать класс затем добавить дополнительный номер или букву ко второму имени класса

0

В JQuery $(this) относится к элементу, из которого был вызван обработчик событий, поэтому вы можете использовать его для выбора других элементов относительно того, что вы нажали при использовании таких функций, как .closest() и .find(). Вы также можете объединить две отдельные функции обработчика кликов в одну.

$(document).ready(function() { 
 
    $(".button").click(function(e) { 
 
    e.preventDefault; 
 
    $(this).closest('.client_container').find(".big_img").fadeToggle("slow"); 
 
    $(this).closest('.client_container').find(".bottom_header").fadeToggle("slow"); 
 
    $(this).closest('.client_container').find('.small_img').fadeToggle(); 
 
    if ($(this).hasClass('button_animate')) { 
 
     $(this).removeClass('button_animate'); 
 
    } else { 
 
     $(this).removeClass('button_animate'); 
 
     $(this).addClass('button_animate'); 
 
    } 
 
    }); 
 
});
.client_container { 
 
    position: relative; 
 
    max-width: 300px; 
 
    height: 373px; 
 
    margin-top: 50px; 
 
    background-color: #00ACC1; 
 
    box-shadow: 5px 5px 4px 0px rgba(35, 31, 32, 0.2); 
 
} 
 
.button { 
 
    position: absolute; 
 
    right: 20px; 
 
    top: 50px; 
 
    width: 46px; 
 
    height: 46px; 
 
    border-radius: 50%; 
 
    border: none; 
 
    background-color: #00838F; 
 
    box-shadow: 5px 5px 4px 0px rgba(35, 31, 32, 0.2); 
 
    cursor: pointer; 
 
    transition: margin-top .5s ease-in-out; 
 
} 
 
.button_animate { 
 
    margin-top: 228px; 
 
} 
 
.big_img { 
 
    position: absolute; 
 
    top: 0px; 
 
    left: 0px; 
 
} 
 
.header { 
 
    position: absolute; 
 
    margin: 0 auto; 
 
    top: 0; 
 
    left: 0; 
 
    width: 100%; 
 
    height: 76px; 
 
    background-color: #0097A7; 
 
} 
 
p { 
 
    margin: 47px 0 0 15px; 
 
} 
 
.footer { 
 
    position: absolute; 
 
    bottom: 0; 
 
    left: 0; 
 
    width: 100%; 
 
    height: 73px; 
 
    background-color: #0097A7; 
 
} 
 
p { 
 
    margin: 10px 0 0 12px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="client_container"> 
 
    <div class="header"></div> 
 
    <div class="footer"></div> 
 
    <img class="big_img" src="http://lorempixel.com/output/people-q-c-300-300-7.jpg"> 
 
    <div class="button button_animate"></div> 
 
</div> 
 

 
<div class="client_container"> 
 
    <div class="header"></div> 
 
    <div class="footer"></div> 
 
    <img class="big_img" src="http://lorempixel.com/output/people-q-c-300-300-7.jpg"> 
 
    <div class="button button_animate"></div> 
 
</div>

Убедитесь, что проверка https://learn.jquery.com/

+0

Спасибо! – gfodor

Смежные вопросы