views:

144

answers:

2

I have a list of items

<div id="item1">somestuff</div>
<div id="item2">somestuff</div>
<div id="item3">somestuff</div>

When someone clicks on one of these, I need to take some actions based on the id (the number). Let's say hide it.

How can I make the function generic, and how can I pass the id into the function?

$(document).ready(function()
{
$("#item-howcanImakethisselectorgeneric?").click(function () { 
  $("#item-andhowcanIpasshteidintohere?").hide();
}
}

I'm a javascript/jquery newbie, any help (including rtfm) appreciated.

A: 

try this:

<div id="item1" class="stuff">somestuff</div>
<div id="item2" class="stuff">somestuff</div>
<div id="item3" class="stuff">somestuff</div>

JS:

$(document).ready(function()
{
   $("#item1, #item2, #item3").click(function () { 
     $(this).hide();
   }
}

or even better:

$(document).ready(function()
{
   $("div.stuff").click(function () { 
     $(this).hide();
   }
}

or this if you will be dynamically adding more divs into the page after loading and don't want to explicitly add the event handlers

$(document).ready(function()
{
   $("div.stuff").live("click", function () { 
     $(this).hide();
   }
}
puffpio
if you need to get the actual text of the id within the function, you can use "this.Id"
puffpio
awesome. And to get only the number, so not "item1" but just "1"?
+1  A: 
<div id="item1" class="mygenericClass">somestuff</div>

<div id="item2" class="mygenericClass">somestuff</div>

<div id="item3" class="mygenericClass">somestuff</div>
$(document).ready(function() 
{ 
  $(".mygenericClass").click(function () {  
    //if you want the id then $(this).id
    //if you just want to hide the clicked element then
    $(this).hide(); 
  }); 
} 
John Hartsock
Perfect. How can I get the id without the "item" text, ie. just the number?
var justTheNumber = ($(this).id).replace("item", "")
John Hartsock