Search code examples
jqueryrecurrence

jquery before(), a recurrence function issue


I want to duplicate a div with a class "test2", by clicking on it, with the function before(). The click will also remove the class "test2" on the originel div, and if the user click again on the originel div an alert('ok') will appear. It's working well but if I'm duplicating n times the div, and if I'm clicking one time on the originel div, alert('ok'); will be all n times.

My code is :

<div class="test1 test2">message</div>

<script src="jquery.js"></script>
<script>
$(function () {

function test() {
    $('.test1').click(function(){
            if($(this).hasClass('test2')){
                $(this).before('<div class="test1 test2">message</div>');
                $(this).removeClass('test2');
            }
            else{
                alert('ok');
            }
    test(); 
    });

}

test();

});
</script>

http://jsfiddle.net/manguo_manguo/TNeYk/


Solution

  • Try this one: here at fiddle

     function test() {
       var i=1;
       $(document).on('click', '.test1', function () {
           if ($(this).hasClass('test2')) {
              $(this).before('<div class="test1 test2">message'+ i++ +'</div>');
              $(this).removeClass('test2')
           } else {
              alert('ok');
           }
       });
    }
    $(function () {
       test();
    });