Reputation: 1736
I have a WP Blog with a few DIVs generated through PHP loops. I would like to be able to show additional about a DIV when someone clicks on it.
The code looks like this:
<div class="story item-1">
<div class="story item-2">
<div class="story item-3">
<div class="story item-4">
(etc. Could be any number of these.)
Clicking on one of the items above should make one of the following appear:
<div class="data preview-1">
<div class="data preview-2">
<div class="data preview-3">
<div class="data preview-4">
I'm doing the following:
$('.story').click( function() {
var getNum = jQuery(this).attr('class');
alert('hi ' + getNum);
});
But how do extract the "number" value (1,2,3,4,etc.) of the item I just clicked into a variable? If I can get that into a variable such as "num" I can then easily use jQuery .hide and .show to perform actions. What I have so far gets the entire class value. Just need the number from the second class.
I'd appreciate any help! Thanks!
Upvotes: 2
Views: 904
Reputation: 73102
Of course you could use string manipulation to pull out the id, but I propose a better solution:
On DOMReady
, loop through all the div's, and assign an index to the elements using jQuery's lightweight data storage mechanism, .data()
:
Disclaimer: untested
$(document).ready(function() {
$('div.story').each(function(index) {
$.data(this, "num", index);
});
});
Then you can pull it out in your click:
$('.story').click( function() {
var getNum = $.data(this, "num");
alert('hi ' + getNum);
});
That's just an example, you may end up needed extra metadata, and you can bind whatever you want to the elements, and use them later.
Upvotes: 2
Reputation: 322452
I'd .split()
on the hyphen, and .pop()
the last item (the number) off the resulting array. Then .show()
the appropriate preview.
$('.story').click( function() {
var getNum = this.className.split('-').pop();
$('.data.preview-' + getNum).show();
});
Upvotes: 3
Reputation: 41802
$('.story').click(function() {
var index = /item-(\d)/.exec($(this).attr('class'))[1] - 1;
$('.data').hide().eq(index).show();
});
Upvotes: 0