gpt4 book ai didi

javascript - Jquery 逻辑按单词匹配数对选择选项进行排序

转载 作者:行者123 更新时间:2023-11-30 13:30:48 25 4
gpt4 key购买 nike

我想要类似于Mysql对数据排序的东西,但是在jquery中。我有一个输入和一个选择标签,就像这样 -

enter image description here

我希望根据输入文本的值过滤和排序选择选项。

  • 过滤 或应用于输入文本的逻辑以及要保留的至少包含一个词的所有选项
  • 排序/分组 然后根据匹配数对剩余选项进行排序,这样包含输入中所有单词的选项出现在顶部,然后是少一个单词的选项,依此类推。以下只是一个例子,可能并不准确 -

enter image description here

我已经完成了过滤部分的逻辑。现在是排序部分,我不知道该怎么做。

举个例子,假设输入文本发布了一个包含 5 个单词的字符串。我不知道 jQuery 中是否有类似于 Mysql 的顺序的东西可以返回我排序的选项。所以,我的逻辑是这样的(伪代码)-

var numberOfWords;
sortedOptions = new Array();
for(cnt=numberOfWords; cnt>0; cnt --)
{
find options containing exactly those many words
append them to array sortedOptions
}

现在考虑 numberOfWords = 5 和 cnt=3 的情况。 3 个词有很多可能的组合,我需要检查这些组合以准备具有 3 个词匹配的选项。这很好,但是当字数增加时,代码的时间复杂度如何呢?有没有更好的优化方式?

此检查可能需要在用户键入时(在每个键上)完成,而且我不能如此频繁地访问后端数据库。我还没有找到任何现成的用于相同目的的插件。请检查我之前的问题Any jquery 1.3 compatible plugin to filter dropdown using user text input plus grouping based on number of input strings matched对此。如果您知道任何可以解决问题的插件,请在此处发布。但无论如何都期待解决这个问题。

最佳答案

类似的东西(不完全有效):

$(function(){
var $select = $('#mySelectBox'), nonMatches = [], $text = $('#myTextBox').keyup(function(){
// find all the words
var words = $text.val().split(' '), options = []
// nonMatches is an array of <option>s from the prev search that didn't match
// we put them back in the <select>
for (var i in nonMatches)
$select.append(nonMatches[i])
nonMatches = []
// and clear all the old labels like "1 word match"
$select.find('optgroup').each(function(){
var $this = $(this)
$this.replaceWith($this.html())
})
// if the textbox is blank, dont need to search
if (!words.length)
return
// loop thru each <option>
$select.find('option').each(function(){
var wordCount = 0, $this = $(this), html = ' ' + $this.html().toLowerCase() + ' '
// loop thru each word and check if the <select> contains that word
for (var i in words) {
if (html.indexOf(' ' + words[i].toLowerCase() + ' ') > -1)
wordCount++
}
// if this <option> doesn't have any of the words, save and remove it
if (wordCount == 0)
nonMatches.push($this.remove())
else {
// otherwise, save it to be sorted
if (!options[wordCount])
options[wordCount] = []
options[wordCount].push($this.remove())
}
})
// the options array holds all the <option>s that match; we need to sort it
keys = [], sortedOptions = []
for (var i in options) {
keys.push(i)
}
keys.sort()
keys.reverse()
for (var i in keys)
sortedOptions[keys[i]] = options[keys[i]]
for (var i in sortedOptions) {
// put the matches in the <select>
$select.append('<optgroup label="' + (i == words.length ? 'All' : i) + ' word match">')
for (var j in sortedOptions[i]) {
$select.append(sortedOptions[i][j])
}
$select.append('</optgroup')
}
})
})

关于javascript - Jquery 逻辑按单词匹配数对选择选项进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6857969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com