Luis Fernando
Luis Fernando

Reputation: 25

applying same function to many elements (in order)

any better way to do that (assuming I have 10 a elements, for instance)?

$('#id > a:nth-child(1)').click(function() { changeP(1); return false; });
$('#id > a:nth-child(2)').click(function() { changeP(2); return false; });
$('#id > a:nth-child(3)').click(function() { changeP(3); return false; });

I know 2 possibilities, but I don't particularly like them:

  1. using .bind() with parameter instead of .click()
  2. using .map(return $(this)) and then iterating over the array with an index var

Upvotes: 0

Views: 181

Answers (5)

Joe C.
Joe C.

Reputation: 1538

You're looking for .each(): http://api.jquery.com/each/

$('#id > a').each(function(index){
    $(this).click(function(){
        changeP(index+1);
    });
});

Upvotes: 0

artlung
artlung

Reputation: 33813

$('#id > a').click(function(){
    changeP($(this).index(' #id > a')+1);
    return false;
});

See: index()

This works even if other elements are inserted into the code:

<div id="id">
    <a href="#">1</a>
    <span>hello</span>
    <a href="#">2</a>
    <a href="#">3</a>
    <a href="#">4</a>
</div>

Upvotes: 0

code_burgar
code_burgar

Reputation: 12323

$.each( $('#id > a'), function(index) { 
  $(this).click(function() { 
   changeP(index); return false; });
 });

Upvotes: 0

James Allardice
James Allardice

Reputation: 165991

You can get the index of an element (relative to it's parent) using the index method:

$("#id > a").click(function() {
    changeP($(this).index() + 1);
    return false;
});

You need to add 1 because element indexes start at 0, whereas nth-child starts at 1. This works because jQuery methods tend to apply to all elements in the matched set, so the click event handler is bound to all elements matching the selector.

Upvotes: 2

Pointy
Pointy

Reputation: 413757

You could do this:

$('#id > a').each(function(i) {
  $(this).click(function() { changeP(i); return false; });
});

jQuery will pass in the index of the selected element as the first parameter to the "each" function.

Upvotes: 3

Related Questions