0

I have a html page.This is the code:

<script src="jquery-1.10.1.min.js"></script>
<script>
$('document').ready(function(){
    $(".class-1").click(function(){
        id=this.id;
        alert(id);
        $("#"+id).removeClass("class-1");
        $("#"+id).addClass("class-2");
    });
});
</script>

<style>
.class-1{color:red;}
.class-2{color:blue;}
</style>

<div class="class-1" id="id-1">sth</div>

When I click the div for the first time, page alerts the id, and the class and color changes.

The problem: When I click on it for the second and third time, it alerts the id again, But it shouldn't. Because the class is changed. So what is the problem?

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
Faridzs
  • 672
  • 8
  • 23
  • 3
    The problem in the duplicate isn't exactly the same, but the solution is. The event handler is bound to the element. Even if you chance the class of that element, the handler is still bound to it. – Jason P Aug 19 '13 at 13:45
  • 1
    You'll likely need to use an [`on`](http://api.jquery.com/on/) binding. – Joachim Isaksson Aug 19 '13 at 13:47

1 Answers1

9

Your code:

  1. Finds all the elements that matches the selector
  2. Binds an event handler to those elements

When you remove the class, the selector no longer matches, but the event handler has already been bound to the element.

You need to use a delegated event handler (which checks that the target element matches the selector you are using each time the event handler is called).

For example:

$(document).on('click', '.x', function () {
  $(this).removeClass('x');
  alert('x');
});
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335