[英]jQuery click events working only for once, but second time its not
jQuery的單擊事件僅此一次合作,但第二次它不是小提琴
$('.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')
}
})
})
使用事件委托來處理動態更改的類。
$(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() {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.