16

I tried to find all ids starting with the string "matchItem_" and define a click-event for each. onclick i want wo execute a script with a URL parameter and change the image in this id-element. Unfortunately my syntax isn't right, I also tried with .each.function but I didn't get it.

$('[id^="matchItem_"]').each {
    
    $(this).click(){
     //...execute my script.php?urlparam=xx....;
     $(this).find('img').attr('src','/admin/images/ok.png');
    }

}
Jan Schultke
  • 5,808
  • 1
  • 22
  • 57
michbeck
  • 715
  • 3
  • 9
  • 15
  • Possible duplicate: http://stackoverflow.com/questions/190253/jquery-selector-regular-expressions – PhD Aug 08 '11 at 16:21

2 Answers2

29

You don't need the each:

$('[id^="matchItem_"]').click(function() {
   // do something
   $(this).find('img').attr('src','/admin/images/ok.png');
});
BenMorel
  • 31,815
  • 47
  • 169
  • 296
Mrchief
  • 73,270
  • 19
  • 138
  • 185
17

Your syntax is invalid because you forgot the functions.

$('[id^="matchItem_"]').each(function() {
    $(this).click(function(){
           //...execute my script.php?urlparam=xx....;
         $(this).find('img').attr('src','/admin/images/ok.png');
    });
});

Or if all you're doing is assigning the .click() handler, you can do it without the .each().

$('[id^="matchItem_"]').click(function(){
       //...execute my script.php?urlparam=xx....;
     $(this).find('img').attr('src','/admin/images/ok.png');    
});

This is because most jQuery methods will automatically act on every element in the jQuery object.

(edited to add closing parenthesis in code)

luke_mclachlan
  • 1,019
  • 15
  • 34
user113716
  • 310,407
  • 61
  • 442
  • 435
  • @michbeck: You're welcome. By the way, it if all the elements are of the same tag type, like `
    `, you'll get better performance if you include the tag in your selector. `$('div[id^="matchItem_"]')`
    – user113716 Aug 08 '11 at 16:41