需要一些jQuery建议......
我在DOM div中有这样的分隔条目:
<div class="my-data">collie; german shepherd;</div>
<div class="my-data">collie; cocker spaniel; pug; poodle;</div>
<div class="my-data">poodle; german shepherd;</div>
我需要将其转换为删除了重复项的按字母顺序排列的列表:
<ul id="new-list">
<li>cocker spaniel</li>
<li>collie</li>
<li>german shepherd</li>
<li>poodle</li>
<li>pug</li>
</ul>
尝试确定实现此目的的最快的jQuery方法;当页面加载时,我将在页面上有大约500个div进行转换。
答案 0 :(得分:1)
var $myData = $('.my-data').detach(), list = [], listHtml = ['<ul><li>'];
$myData.each(function(i, el) {
var txt = $(el).text().split(';');
$.each(txt, function(idx, val) {
var val = $.trim(val);
if (val && val != '' && $.inArray(val, list) == -1) {
list.push(val);
}
});
});
list.sort();
listHtml.push(list.join('</li><li>'));
listHtml.push('</li></ul>');
$('body').append(listHtml.join(''));
答案 1 :(得分:0)
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var sorting = [];
var divs = $('.my-data');
$.each(divs,function(){
var instr = $(this).html().split(';');
for(i=0;i<instr.length;i++){
if(instr[i] !=""){
sorting.push(instr[i]);
}
};
});
sorting.sort();
var str = '<ul id="new-list">';
for(i=0;i<sorting.length;i++){
if((sorting[i] != sorting[i+1]) && sorting[i+1] !="undefined"){
str += '<li>'+sorting[i]+'</li>';
}
};
str += '</ul>';
$('#container').html(str);
});
</script>
</head>
<body>
<div class="my-data">collie; german shepherd;</div>
<div class="my-data">collie; cocker spaniel; pug; poodle;</div>
<div class="my-data">poodle; german shepherd;</div>
<div id="container" ></div>
</body>
</html>
答案 2 :(得分:0)
这是javascript
var dataArray = [];
$("body").append("<ul id='new-list'></ul>");
var newList = $("#new-list");
$(".my-data").each(function(){
var tempArray = $(this).text().split(";");
for(var temp in tempArray){
var item = tempArray[temp];
if( item !='' && $.inArray(item, dataArray) == -1) {
dataArray.push(item);
newList.append("<li>"+item +"</li>");
}
}
});