jQuery click events working only for once, but second time its not Fiddle
$('.animateBtn').on('click', function() {
$(this).addClass('OFF');
$(this).next('div').addClass('animate');
var btnText = $(this).text('Aniamte ON');
if($(this).next('div').hasClass('animate')) {
$(this).text('Aniamte OFF')
}
$('.OFF').on('click', function() {
if($(this).hasClass('OFF')){
$(this).removeClass('OFF');
$(this).next('div').removeClass('animate');
$(this).text('Aniamte ON')
}
})
})
Use event delegation to deal with dynamically changing classes.
$(document).on('click', '.animateBtn', function () { $(this).addClass('OFF').removeClass('animateBtn'); $(this).next('div').addClass('animate'); var btnText = $(this).text('Aniamte ON'); $(this).text('Aniamte OFF'); }); $(document).on('click', '.OFF', function () { $(this).removeClass('OFF').addClass('animateBtn'); $(this).next('div').removeClass('animate'); $(this).text('Aniamte ON') });
.animate { background: url(http://lorempixel.com/100/100); height: 100px; width: 100px; -webkit-animation: slide 2s linear infinite; -moz-animation: slide 2s linear; animation: slide 2s linear infinite; } @-webkit-keyframes slide { 0% { background-position: 0 0; } 100% { background-position: 100px 0; } } @-moz-keyframes slide { 0% { background-position: 0 0; } 100% { background-position: 100px 0; } } @keyframes slide { 0% { background-position: 0 0; } 100% { background-position: 100px 0; } }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <button class="animateBtn">Animate ON</button> <div> </div> </div>
将事件委托用于动态元素
$(document).on('click','.OFF', function() {
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.