It's hard to say exactly, since your example is probably simplified. But try a more general selector, rather than selecting them by ID (you can use $('[id^="q"]')
, but that's not really best practice). You're using the ID element like a class, which isn't really what id
is for.
If you give them all a class
attribute like class="q"
for the buttons and class="item"
for the targets, you can do something like this:
$('.q').each(function(index) {
var targetItem = $('.item').eq(index);
$(this).click(function() {
clearIt();
targetItem.show();
});
});
But it'll be easier, safer, and better practice to specify the target of each clickable element right there in the markup:
<a href="#" class="p" target-index="01">p01</a>
<a href="#" class="p" target-index="02">p02</a>
<div class="item" item-index="01">item01</div>
<div class="item" item-index="02">item02</div>
Then their order and location on the page won't matter. You can just select them directly:
var num = $(this).attr('target-index');
var targetItem = $('.item[item-index="' + num + '"]');
Finally (and my preferred advice), you can put the ID of the target right into the button itself:
<a href="#" class="p" for="item01">p01</a>
<div id="item01">item01</div>
Then you can select the target quickly, safely, and regardless of its location:
var targetItem = $('#' + $(this).attr('for'));
Edit 1:
My first snippet makes assumptions about the order of your elements, because there are lots of ways for the clicked element to be associated with the target item. Only you know the rules for your markup, so only you know what assumptions will work. For example:
var targetItem = $('#' + $(this).attr('id').replace(/^q/, 'item'));
var targetItem = $(this).siblings('[id^="item"]');
var targetItem = $(this).children('[id^="item"]');
var targetItem = $(this).parents('[id^="item"]');
var targetItem = $(this).find('[id^="item"]');
If you don't use the target-index
technique I suggested, you'll have to make at least some assumptions based on your knowledge of the HTML.
Edit 2:
Based on your comment that you're trying to trigger the handlers, rather than improve your event-binding code, you can do that like this:
//quick and dirty zero-padding function from http://stackoverflow.com/q/10073699/399649
var pad = function(num, size) {
return (Math.pow(10, size) + ~~num).toString().substring(1);
};
for(var i = 1; i < $('[id^="q"]').length; i++) {
var index = pad(i, 2);
$('#q' + index).trigger('click');
}