javascript - 第一次执行代码时将永久值存储在变量中,JavaScript

标签 javascript c# arrays

function filterListBox() {
  debugger;
  var txtValue = document.getElementById('<%=txtSearchUser.ClientID %>').value; //to get entered value to search
  var lstbox = document.getElementById('<%=lstMembers.ClientID %>');
  var opt;
  var array = new Array();
  var array1 = new Array();
  array = lstbox.options; //array value is 8

  if (txtValue != '') {
    for (var i = 0; i < array.length; i++) {
      if (array[i].innerText.toLowerCase().indexOf(txtValue) > -1) {
        opt = document.createElement("option");
        opt.text = array[i].text;
        opt.value = array[i].value;
        array1.push(opt); // only pushes names that match the search filter

      }

    }
    lstbox.options.length = 0;
    for (var i = 0; i < array1.length; i++) {
      opt = document.createElement("option");
      opt.text = array1[i].text;
      opt.value = array1[i].value;
      lstbox.add(opt); // displays the pushed names that matched the search filter
    }

  }
  else {
    lstbox.options.length = 0;
    for (var i = 0; i < array.length; i++) {
      opt = document.createElement("option");
      opt.text = array[i].text;
      opt.value = array[i].value;
      lstbox.add(opt);
    }
  }

}

在上面的代码中,当我第一次运行代码时,变量array的值为8。但是当它进入if(txtValue != '')它开始过滤名称,并仅推送 array1 中与输入值 (txtValue) 匹配的名称。然后它只显示这些名称。

这里的问题是,当我为 txtValue 输入另一个值时,它会在更新的数组选项中搜索该值,而不是在原始数组中。所以返回的结果不正确。我谦虚地请求一个解决方案,将数组重置为其原始选项,并搜索整个数组而不是更新后的数组。

谢谢。任何帮助深表感谢。

最佳答案

先将选项复制到永久数组,然后使用它。

var lstbox, allOptions;
document.addEventListener("DOMContentLoaded", function(event) {
    lstbox = document.getElementById('<%=lstMembers.ClientID %>');
    allOptions = Array.from(lstbox.options);
});

改变

array = lstbox.options;

到此

array = allOptions;

关于javascript - 第一次执行代码时将永久值存储在变量中,JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49104703/

相关文章:

javascript - Bootstrap : accordian not collpased in beginning

javascript - 使用 jquery 更改值时,asp.net 文本框更改事件未触发

c# - 对数据表中的行进行分组

arrays - Google Cloud - BigQuery - 在结构中转置 2 个字符串列

ios - 快速迭代 JSON

javascript - 使用多个小数点对 'numbers' 进行排序

javascript - 行数多的表更新慢

javascript - 是否有可能在客户端有一个进度条链接到 saveAs() 的进度?

c# - 用 C++ 开发 Win32 应用程序比用 C# 开发 .NET 应用程序有什么优势?

c - 尝试在 C 中释放字符数组的数组会导致双重释放或损坏