levi
levi

Reputation: 3521

Click Not to Fire After Selector is Changed

I have an anchor in the website. When someone clicks on it I do smth in jquery and change name, but when it is clicked again event is fired, despite I've changed it's name. code here:

$(".like_cont a[name=like]").click(function (e) {
                alert("W");
                var t = $(this);

                t.find("img").attr("src", "images/like_icon.png");

                var ls = parseInt(t.next().next()) + 1;
                t.next().next().text(ls);

                var params = "Like|" + t.attr("lik");
                CallServer(params, "");

                t.attr("name", "liked");
                e.preventDefault();
            });

after Click name is liked but another click events Fire. How to change selector to preserve firing?

Upvotes: 0

Views: 47

Answers (2)

nnnnnn
nnnnnn

Reputation: 150080

You can call .off() to remove the event handler as per Iridio's answer.

Or you can use a delegated event handling model:

$(".like_cont").on("click", "a[name=like]", function (e) {
    ...
});

This relies on the fact that click (and most other) events bubble up from the source element through all their containing elements. So with a handler bound with this syntax of .on(), whenever a click occurs on (in this example) the ".like_cont" element(s), jQuery tests the event's source element to see if it matches the selector in the second parameter, "a[name=like]" - if it does then the function is called, otherwise it is not.

In other words, with a delegated handling model the function will be called only if the clicked element matches the selector in the second parameter at the time the event occurs.

With a "standard" handler bound with .click(), or bound with .on() without that second parameter, the event is bound directly to the element(s) that matched the selector at the time the event was bound - regardless of whether such elements still match that selector at the time of the event. (Not that that is a bad thing - sometimes it's exactly what you need, just not in your present case.)

Upvotes: 1

Iridio
Iridio

Reputation: 9271

One possible way would be to call .off() to remove the click event from your object.

Upvotes: 1

Related Questions