如何限制使用原始javascript自动完成功能的匹配?

时间:2019-02-01 17:30:10

标签: javascript django

我为Django应用创建了喜欢/不喜欢的功能。

它使用jQuery / ajax并可以正常工作,但是它破坏了我的Devbridge自动完成搜索(https://github.com/devbridge/jQuery-Autocomplete)。

我已经决定更换Devbridge自动完成与香草JS自动完成从这里:https://www.w3schools.com/howto/howto_js_autocomplete.asp

问题是我的数组中有超过10,000个项目,因此当您输入前几个字母时,它会产生100或数千个匹配项。

我想限制比赛的数量。任何帮助深表感谢。我已经包含了我猜测是最相关的代码。有关完整的代码,请查看链接。

<FormItem validateStatus="validating">
    {getFieldDecorator('phoneNumber', {rules: [
        { required: true, message: 'Please input your phone number.' },
        { len: 10, message: 'Phone number should be 10 digits long.' },
        { validator: this.numbersValidator },
        { validator: this.mobileCountryCodeValidator(this.props.form) },
     ]})(
          <Input placeholder="Enter Mobile Number" />
     )}
</FormItem>

1 个答案:

答案 0 :(得分:0)

  

问题是我的数组中有超过10,000个项目,因此当您输入前几个字母时,它会产生100或数千个匹配项...我想限制匹配项的数量。

因此,我们找出在数组中迭代的位置,并为可添加到列表中的项目数添加上限。

// This is where it loops all the items in the array
for (i = 0; i < arr.length; i++) {

    ...

    // This is the logic which will dictate if an item is added to the list
    if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
        ...
    }
}

让我们为可以添加到列表中的匹配项增加一个限制,方法是一旦达到上限,就退出循环。

let maxMatches = 10;
let matches = 0;
// Stop this loop once maximum matches have been found
for (i = 0; i < arr.length; i++) {
    ...

    // This is the logic which will dictate if an item is added to the list
    if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
        // Another match has been found, increment counter
        matches = matches + 1;
        ...
    }

    // Break the loop if we hit max number of matches
    if (matches >= maxMatches) {
        break;
    }
}

希望这会有所帮助!