php - Long delay when my jQuery function fires due to a large amount of values in my select form elements
问题描述
I have a .php
page with about two hundred select
form elements on it. The element values are being populated by a .txt
file in the same directory using PHP:
<?php
$schoolselected = 'schools.txt';
$eachlines1 = file($schoolselected, FILE_IGNORE_NEW_LINES);
?>
and
<select name="schoolselected001">
<option value="" disabled selected>Select School...</option>
<option value=" " <?php if(isset($_POST['schoolselected001'])) echo "selected"; ?>></option>
<?php foreach($eachlines1 as $lines1){
echo "<option value='".$lines1."'>$lines1</option>";
}?>
</select>
Each select
form element have the same name but with 001 through 200.
I'm using this jQuery function to disable an option
when selected to prevent doubling up:
<script>
$(document).ready(function(){
$('select[name*=schoolselected]').on('click', function() {
$('option').prop('disabled', false);
$('select[name*=schoolselected]').each(function() {
var val = this.value;
$('select[name*=schoolselected]').not(this).find('option').filter(function() {
return this.value === val;
}).prop('disabled', true);
});
}).change();
});
</script>
Everything works perfectly and there was no delay when I tested with ten values
but now with two hundred values
, there is a 10-12 second delay each time I click any of the select
form elements.
Are there any tweaks I can do to the existing code to remove the delay? Or maybe I'm taking the wrong approach? I looked into caching the data but had no luck finding a solution. If I disable the jQuery function there is zero delay. Any help or suggestions would be appreciated.
解决方案
So many questions to what you are trying to achieve
Why 200 select dropdowns?
Why did you use 'on click' on a select? you want 'on change' event right?
your code is slow because you are iterating twice over your 200 selects
here is the working code
<script>
$(document).ready(function(){
var lastSelectedValue = {};
$('select[name*=schoolselected]').on('change', function() {
var currentSelect = this.attributes.name.value;
var oldValue = lastSelectedValue[currentSelect];
lastSelectedValue[currentSelect] = this.value;
$('select[name*=schoolselected]').not(this).each(function() {
if(oldValue){
$(this).find("option[value='"+oldValue+"']").prop('disabled', false);
}
$(this).find("option[value='"+lastSelectedValue[currentSelect]+"']").prop('disabled', true);
});
});
});
</script>
推荐阅读
- angular - Type '{Property: string, Property2: string} 不可分配给 Observable 类型
- c# - 如何在 ASP.NET Core 中使用 HttpContext.Current
- java - 添加新的组合框 Java
- python - 如何通过python click框架定义这个命令?
- state-machine - Spring 状态机 UML 保留在内存中
- c++ - 使用 multiset_of 提升 bimap 查找
- python - re.findall() 可以返回 None 吗?
- c# - 以编程方式备份 SQL Server 数据库,而不将其记录/包含在备份历史记录中
- ios - 如何快速重启计时器
- regex - linux查找名称中带有可选字符的文件