John x
John x

Reputation: 4031

Select a specific anchor jquery

i have 6 links on my page like

<a rel='popup'></a>

i am selecting the link as

$(document).ready(function(){
    var popUp = $("a[rel='popup']");
    popUp.click(function(e){
        e.preventDefault();         
        alert("pop clicked");  <-- apperaring 6 times
        var thiis = $(this);
        var href = thiis.attr("href");
        });
    });

the problem is alert pop clicked is appearing 6 times, can anybody help me figure out the problem. I want it to appear only once Thanks.

Upvotes: 0

Views: 159

Answers (3)

user113716
user113716

Reputation: 322622

Since the code is reduced, the only thing I can think of is that your actual code is calling the alert() (or whatever code is repeating) as a callback to the animate()[docs] method (or some other method that accepts a callback).

popUp.animate({/***/}, 1000, function() {

    alert("pop clicked"); // this will run 6 times

});

So if you're running some code off the cached set of popUp elements, and it takes a callback, the callback will run once for each element.


EDIT: Another posibility would be that you're caching the set, using the each()[docs] method, but applying the handler to the entire set during every iteration. That would cause 6 handlers to be attached to each element instead of one.

$(document).ready(function(){
    var popUp = $("a[rel='popup']");

    popUp.each(function() {

         // this would cause 6 handlers to be assigned to each element 
         //    instead of one
       popUp.click(function(e){
            e.preventDefault();         
            alert("pop clicked");  
            var thiis = $(this);
            var href = thiis.attr("href");
       });
    });
});

If this is the case, then instead of:

popUp.click(function(e){

you should do:

$(this).click(function(e){

Upvotes: 2

Ēriks Daliba
Ēriks Daliba

Reputation: 718

try this one:

var popUp = $("a[rel='popup']");

$(popUp).each(function(n, item){
    $(this).click(function(e){

       // your stuff goes here
    }
});

Upvotes: 1

CResults
CResults

Reputation: 5105

Have a look at this. I've taken your code, put it in a table and it is running fine.

http://jsfiddle.net/93Mat/

Upvotes: 1

Related Questions