Regroup element with jquery
I have a number of messages on my page like this:
<div class="messages">A</div>
<div class="messages">B</div>
<div cla开发者_JAVA百科ss="messages">A</div>
<div class="messages">C</div>
is there any way with jQuery (no PHP) to count and regroup 2 div A like this:
<div class="messages">A</div><span>2</span>
<div class="messages">B</div>
<div class="messages">C</div>
Thank you.
You can start out with something like this:
$('div.messages:contains(A)');
How you build that into your other code would depend on what you know ahead of time.
If you don't know what the possible values are you'll probably end up with something like this:
var $messages = $('div.messages');
var counts = {};
$messages.each(function (i, div) {
var $div = $(div);
if (counts[$div.text()] == undefined) { counts[$div.text()] = 0; }
++counts[$div.text()];
});
That'll count up the divs based on their content. Then you add something that loops over the counts.
This should help you :)
"use strict";
/*global $*/
$(function () {
var selector = '.messages';
$(selector).each(function (i, div) {
var similar = $(selector + ':gt(' + i + ')').filter(function (index) {
return $(this).text() === $(div).text();
});
if (similar.length) {
var count = similar.remove().length + 1;
$(this).after(count);
}
});
});
wbr, Roman
精彩评论