我需要将 item div组合在同一个父级中(在 Flute,Piccolo ... 下),但这些类名是可变的。我尝试了很多方法但没有成功。
https://jsfiddle.net/3hm7ngk7/1/
<div class="score">
<div class="Flute">
<div class="item">item 1</div>
<div class="item">item 2</div>
</div>
<div class="Piccolo">
<div class="item">item 3</div>
<div class="item">item 4</div>
</div>
<div class="Flute">
<div class="item">item 5</div>
<div class="item">item 6</div>
</div>
<div class="Piccolo">
<div class="item">item 7</div>
<div class="item">item 8</div>
</div>
<div class="Clarinet_in_Bb">
<div class="item">item 9</div>
<div class="item">item 10</div>
</div>
</div>
应该看
<div class="score">
<div class="Flute">
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="item">item 5</div>
<div class="item">item 6</div>
</div>
<div class="Piccolo">
<div class="item">item 3</div>
<div class="item">item 4</div>
<div class="item">item 7</div>
<div class="item">item 8</div>
</div>
<div class="Clarinet in Bb">
<div class="item">item 9</div>
<div class="item">item 10</div>
</div>
</div>
答案 0 :(得分:1)
您的代码正在运行,但它不是动态的,我使用每个函数更新以通过类score
的所有直接子项,动态组合具有相同名称的类。
$('.score').children('div').each
会识别.score
内部基本上和你一样
$('.score').children('div').each(function(i, obj) {
let rows = $('.' + obj.className);
rows.first().append(rows.not(':first', this).children())
rows.not(':first').remove();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="score">
<div class="Flute">
<div class="item">item 1</div>
<div class="item">item 2</div>
</div>
<div class="Piccolo">
<div class="item">item 3</div>
<div class="item">item 4</div>
</div>
<div class="Flute">
<div class="item">item 5</div>
<div class="item">item 6</div>
</div>
<div class="Piccolo">
<div class="item">item 7</div>
<div class="item">item 8</div>
</div>
<div class="Clarinet in Bb">
<div class="item">item 9</div>
<div class="item">item 10</div>
</div>
</div>
&#13;