我希望在与一个单词进行比较之后对列表标记进行排序,例如,如果多个单词具有单词"一个"所以它应该先排序,然后检查其他语句中的其他单词,如" two"在剩余的陈述中所以这个陈述有"两个"单词应该在包含" one"的语句之后。那么伙计们请帮助我如何编写逻辑。看一下我的代码,我只用于按字母顺序排序...... (根据下面代码中给出的状态) 示例:喜欢
<script id="template" type="text/html">
<ul class="checklist" data-role="listview" data-inset="true" data-autodividers="true" id="mylist">
{{#container}}
{{#nid}}<li><a href="checklist-detail.html?nid={{nid}}">{{name}} - {{status}} {{#date}}<br/>
<span class="due-date">{{date}}</span>{{/date}}</a></li>{{/nid}}
{{/container}}
</ul>
</script>
look once my javascript code but this is not for my desire code it is only
for sort alphabetically (help me in this code that how to i write
condition or logic for sort according to particular word comparison)
var mylist = $('ul');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
var compA = $(a).text().toUpperCase();
var compB = $(b).text().toUpperCase();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
});
$.each(listitems, function(idx, itm) { mylist.append(itm); });
答案 0 :(得分:0)
您可以根据标记中是否包含预定义排序单词列表中的单词,为标记指定分数。例如:
var ordered_words = ["kumar", "koul", "simon"]
var tags = ["manoj kumar", "rohit koul", "sachin kumar", "simon f (me)"]
var scored_tags = []
var i = 0, tag
while (tag = tags[i]) {
var j = 0, word, found = false
while (found == false && j < ordered_words.length) {
word = ordered_words[j]
if (tag.indexOf(word) != -1) {
scored_tags.push({tag: tag, score: j})
found = true
}
j++
}
i++
}
console.log(scored_tags)
这将输出:
[ { tag: 'manoj kumar', score: 0 },
{ tag: 'rohit koul', score: 1 },
{ tag: 'sachin kumar', score: 0 },
{ tag: 'simon f (me)', score: 2 } ]
然后,您可以使用score参数对此数组进行排序,使用以下内容:
scored_tags.sort(function(a, b) {
var compA = a.score
var compB = b.score
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
});
以下是您可以使用的代码: