gpt4 book ai didi

javascript - select2 本地存储的下拉值

转载 作者:行者123 更新时间:2023-11-28 04:15:26 24 4
gpt4 key购买 nike

我有多个 select2 下拉菜单。它们的值是从各自的 json 文件加载的。表单加载速度很慢。

  1. 我想将它们的 json 文件合并到一个文件中。如何更改我的 JavaScript 以从一个 json 文件读取?
  2. 是否可以将下拉值保存在本地,这样当第二次加载表单时,它会从内存中读取而不是再次读取json文件。

function mySelect2(file,field) {
$.getJSON(file, function(obj) {
$.each(obj, function(key, value) {
$(field).select2({
data: [
{
id: value,
text: key
}
]
});
});
});
}
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
mySelect2("../data/contactsourcesources.json",'#source_of_contact');
mySelect2("../data/levelofstudysources.json",'#degree');
//mySelect2("../data/institutionssources.json",'#uni');
//mySelect2("../data/countries.json",'#countryorigin');
mySelect2("../data/degreessources.json",'#course');
});
</script>
</head>
<body >
<section>
<label for="source_of_contact">
Contact Method:
<select class="source_of_contact" id="source_of_contact" name="source_of_contact">
</select>
</label>

<label for="degree" class="lbl-text">Degree Type:<span id="required">*</span>
<select class="degree" id="degree" name="degree">
</select>
</label>
</section>
</body>
</html>

Json 文件:

{"Caf\u00e9 Connect\n":"7e0a7146","Academic Advising Day\n":"academic_advising_day"}

我想将 JsonJavaScript 更改为

{"source_of_contact":{"Caf\u00e9 Connect\n":"7e0a7146","Academic Advising Day\n":"academic_advising_day"}}

function mySelect2(file,field) {
$.getJSON(file, function(obj) {
// obj.field, how do I get value of field? I want to be like this
// obj.source_of_contact
$.each(obj.field, function(key, value) {
$(field).select2({
data: [
{
id: value,
text: key
}
]
});
});
});}

最佳答案

不要使用CDN,下载js本地副本使用。这会增加一点时间,

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

第二,为了使其加载数据更快,不要在文档准备好时调用所有 GetJSOn 函数,而是在下拉值更改时依次调用每个函数。

关于javascript - select2 本地存储的下拉值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45911733/

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