是否可以按顺序用data-term
中的字符串替换表中所有类名的一部分?
这是原始标记:
<div class="query" data-term="Africa"></div>
<div class="query" data-term="Asia"></div>
<div class="query" data-term="Europe"></div>
<table><thead><tr>
<td>Africa</td><td>Asia</td><td>Europe</td>
</tr></thead>
<tbody>
<tr><td class="replacemefirst">Info</td><td class="replacemefirst">location</td><td class="replacemefirst">find</td></tr>
<tr><td class="replacemesecond">world</td><td class="replacemesecond">somewhere</td><td class="replacemesecond">belong</td></tr>
</tbody>
</table>
我想要实现的是获取数据属性并按照以下顺序替换表中的类:
<table><thead><tr>
<td>Africa</td><td>Asia</td><td>Europe</td>
</tr></thead>
<tbody>
<tr><td class="Africafirst">Info</td><td class="Asiafirst">location</td><td class="Europefirst">find</td></tr>
<tr><td class="Africasecond">world</td><td class="Asiasecond">somewhere</td><td class="Europesecond">belong</td></tr>
</tbody>
</table>
以下代码并没有真正起作用。我不确定如何查找每个replacemefirst
和replacemesecond
并将其替换为数据属性。有什么建议吗?
$( document ).ready(function() {
$(".query").each(function() {
var div_terms = $(this).data('term'),
replaceme = $('.replacemefirst').attr('class'),
// not sure how to approach this part
x = replaceme.replace("replaceme",div_terms);
$('.replaceme??').addClass(x);
$('.replaceme??').attr('class',x);
});
});
答案 0 :(得分:1)
所有这些看起来都很可疑,但你可以尝试这个http://jsfiddle.net/tarabyte/cHtT6/14/
$( document ).ready(function() {
$(".query").each(function() {
var term = $(this).data('term'),
replaceme = 'replaceme',
first = replaceme + 'first',
second = replaceme + 'second',
target1 = $('.' + first).eq(0),
target2 = $('.' + second).eq(0);
target1.toggleClass([first, first.replace(replaceme, term)].join(' '));
target2.toggleClass([second, second.replace(replaceme, term)].join(' '));
});
});
或更多DRY版本http://jsfiddle.net/tarabyte/cHtT6/16/
$(function() {
var terms = $('.query').map(function(){
return $(this).data('term');
}), selectors = ['first', 'second'];
$.each(selectors, function(_, name) {
var cls = 'replaceme' + name;
$('.' + cls).toggleClass(function(idx){
return [cls, terms[idx] + name].join(' ');
})
})
});