Q:

jQuery .on not working with link after class is changed

In my code below, I change the class of a link from user to red. The idea is that a link with class red should not work on click. But it still does. Why does this happen? I was about to use live, but read it's deprecated and I should be using on.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>

<script type="text/javascript" src="http://localhost/site/scripts/jQuery.js"></script>

<script type="text/css">
.red{
color:red;
}
</script>

<script type="text/javascript">
$(document).ready(function() {
    $(".user").on("click",function() {
    alert('Was Clicked');
        var idPri = $(this).data("id");
        var idSec = $(this).data("sec");
        $('.user[data-id="'+idPri+'"][data-sec="'+idSec+'"]').removeClass('user').addClass('red');
        $('.h2[data-id="'+idSec+'"]').find('span[data-sec="'+idSec+'"].user').remove();
        });
        return false;
    });
</script>
</head>
<body>

<div id="container">
    <div class="h2" data-id="2">Who is your favorite Math teacher?
        <div>* User Name <span class="user" data-id="3" data-sec="2">Like</span></div>
        <div>* User Name <span class="user" data-id="4" data-sec="2">Like</span></div>
        <div>* User Name <span class="user" data-id="5" data-sec="2">Like</span></div>
        <div>* User Name <span class="user" data-id="6" data-sec="2">Like</span></div>
        <div>* User Name <span class="user" data-id="7" data-sec="2">Like</span></div>
    </div>
</div>

</body>
</html>

A:

You're using direct event handlers. When you call $(".user").on("click",function() {, the event handlers are attached to your elements. Later when you change your class to red, the event handlers are already attached and will still fire. In your case, you could try delegated event handlers:
$("#container").on("click",".user",function() {

Delegated event handlers, on the other hand, are evaluated dynamically because the event handlers are not attached directly to the elements, but to the container instead.

A:

You can try using delegated events.But If you want to use .user class itself, then you can do something like this:
$(document).ready(function() {
$(".user").on("click",function() {
    if($(this).hasClass('red')){
        return false;
    }
alert('Was Clicked');
    var idPri = $(this).data("id");
    var idSec = $(this).data("sec");

    $('.user[data-id="'+idPri+'"][data-sec="'+idSec+'"]').removeClass('user').addClass('red');
    $('.h2[data-id="'+idSec+'"]').find('span[data-sec="'+idSec+'"].user').remove();
    });

  });

check the demo here:http://jsfiddle.net/PkBAq/

