jQuery点击事件只工作一次,但第二次不工作

时间:2015-05-26 07:12:02

标签: javascript jquery html css

jQuery点击事件只能工作一次,但第二次不是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')  
        }
    })    
})

2 个答案:

答案 0 :(得分:1)

使用事件委托来处理动态变化的类。



$(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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

将动态元素的事件委托用于

 $(document).on('click','.OFF', function() {