I\'m having several div\'s #mydiv1
, #mydiv2
, #mydiv3
, ... and want to assign click handlers to them:
$(document).ready
You can get by with assigning the click handler once (or at least not making many unnecessary closures). Put all the divs in one class mydivs
, then:
$(document).ready(function(){
$('.mydivs').click(function(){
// Get the number starting from the ID's 6th character
// This assumes that the common prefix is "mydiv"
var i = Number(this.id.slice(5));
alert('you clicked ' + i);
});
});
This looks at the element's ID to get its number, using the slice string method to strip the initial letters off.
Note: It may be better to use
$('#divcontainer').on('click', '.mydivs', function(){
instead of
$('.mydivs').click(function(){