Take <span> class and put in <a> attribute jquery
I have html like this.
<span class="gallery-open-item year-icon-Yes 2010">
<a href="/year/none">
</a>
</span>
I need to check using jQuery if span.gallery-open-item
has year-icon-Yes
class, and if so take the next (for this example is 2010) class and place it in the href
attribute like th开发者_JAVA技巧is:
<a href="/year/2010"/>
All this I need in jQuery or JavaScript.
I have done some experiments but I can't take 2010 to normal javascript variable. Any ideas?
Sorry for my English.
Here's another approach. Tested, working.
$('.gallery-open-item.year-icon-Yes').each(function(){
that = this;
var classes = $(this).attr('class').split(' ');
$.each(classes, function(i, val) {
if (val.match(/^y-/gi)) {
$('a', that).attr('href', function(){
return this.href.replace('none', val.split('-')[1]);
});
}
});
});
Assumes this markup:
<span class="gallery-open-item year-icon-Yes y-2010">
<a href="/year/none/">
Test
</a>
</span>
How about this:
$('span.gallery-open-item.year-icon-Yes > a').each(function(i, elem) {
$.each($(elem).parent().attr('class').split(' '), function(j, klass) {
// NOTE: use /^y-([\d]*)$/ if years are prefixed with y-
if (year = klass.match(/^([\d]*)$/))
$(elem).attr('href', $(elem).attr('href').replace('none', year[1]));
});
});
This would iterate over every A tag beneath your SPAN tags and fetch the classes from each parent, search these for a number and replace the "next" part.
Update: Added comments for the case you switch to prefixed years.
Update 2: Now tested and working (using Prototype usually *sigh*).
Here's one way of doing it. First, we select the span
tags that have both the classes gallery-open-item
and year-icon-Yes
. Then, for each of them we're going to get an array of classes that the span
tag has. I loop over the class names, and check for the first one that is a number. Finally, modify the a
tag inside the span
to set the desired url.
$(document).ready(function() {
$('span.gallery-open-item.year-icon-Yes').each(function() {
var classNames = $(this).attr('class').split(' ');
for (var i = 0; i < classNames.length; i++)
{
if (!isNaN(classNames[i]))
{
var year = classNames[i];
$(this).find('a').attr('href', '/year/'+year);
break;
}
}
});
});
Edit: Based on the comments that class names should not start with a number, it's pretty easy to make this work for class names of the form y-xxxx
:
$(document).ready(function() {
$('span.gallery-open-item.year-icon-Yes').each(function() {
var classNames = $(this).attr('class').split(' ');
for (var i = 0; i < classNames.length; i++) {
var year = classNames[i].substring(2);
if (!isNaN(year)) {
$(this).find('a').attr('href', '/year/' + year);
break;
}
}
});
});
精彩评论