我有这段代码,想要复制gal1类的数字1,2,3 .... gal2,gal3 ..以及addClass“featured-image”。它不能计算,因为类ga1,gal2,gal3 ..是插入手动manualy没有顺序。所以我要将父类galX和addClass的数量提取到a.featured-imageX。
$('.gal1').find( 'a[href]' ).addClass( 'featured-image1' );
$('.gal2').find( 'a[href]' ).addClass( 'featured-image2' );
$('.gal3').find( 'a[href]' ).addClass( 'featured-image3' );
$('.gal4').find( 'a[href]' ).addClass.....and so on.
我已经搜索并考虑过它,但仍然没有解决方案。
答案 0 :(得分:2)
简单如下:
$('div[class^="gal"]').each(function(){
// in here $(this) is the div[class^="gal"] element
$(this).find('a[href]').addClass(
'featured-image' +
$(this).attr('class').replace (/[^\d.]/g, '') // get the number from the classname from div[class^="gal"]
);
});
/* only to show the class with the number gets added */
.featured-image1 { color: orange; }
.featured-image2 { color: green; }
.featured-image3 { color: fuchsia; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gal1">
<div class="blubb">
<p><a href="#">A TAG</a></p>
</div>
</div>
<div class="gal2">
<div class="blubb">
<p><a href="#">A TAG</a></p>
</div>
</div>
<div class="gal3">
<div class="blubb">
<p><a href="#">A TAG</a></p>
</div>
</div>