JQuery selector: pass on id from array into function
I have a list of items
<div id="item1">somes开发者_如何学Pythontuff</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.
<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();
});
}
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();
}
}
精彩评论