如何在JavaScript中加载和更改默认选项?

q8l4jmvw  于 2023-01-24  发布在  Java
关注(0)|答案(2)|浏览(130)
    • 代码**

我有一个HTML格式的表单:

<label for="alternativeGraph">Alternative graphs could be seen here:</label>
         <select id="selGraph" onchange="graphUpdate()" aria-label="Graph">
                <option value="1" selected="selected">Graph 1 (default)</option>
                <option value="2">Graph 2</option>
                <option value="3">Graph 3</option>
                <option value="4">Graph 4</option>
                <option value="5">Graph 5</option>
            </select>
      <button type="button" onclick="setDefault()"> Change default graph</button>

我计划在页面加载时将Graph 1作为默认选项加载,并使用setDefault()函数更改默认图表。下面是我的JavaScript代码:

function render(filename) {
fetch(filename).then(response  => response.text()).then(textAsString => 
     renderString(textAsString));
}

   
function graphUpdate(){
    let value = document.querySelector('#selGraph');
    let graph = ["graph_1.gv", "graph_2.gv", "graph_3.gv", "graph_4.gv", "graph_5.gv"]
    render(graph[value.selectedIndex]);
    
}

// function setDefault(){ # I am not sure about what should be added here...
//     let new_default_graph = document.querySelector("#selGraph");
//     new_default_graph.value = 
    

// }
    • 问题**

主要的问题是当我加载网站时,尽管我选择了默认图表,但图表1("graph_1.gv"文件)没有加载。只有当我单击下拉表单时,图表才显示出来。(但其他图表仍然加载)。

    • 问题:**

有没有什么方法可以从我选择的选项中读取并从头加载它?还有,我应该如何处理我的setDefault()函数,以便当用户选择选项3时,网站可以在刷新时将此选项保存为默认选项?

7fyelxc5

7fyelxc51#

由于网页加载所有DOM组件需要一定的时间,所以也许您应该在脚本中包含一个window. onload事件函数,以便在页面第一次完全加载后调用graphUpdate()函数:

window.onload = graphUpdate;

更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
要保存所选值,可以使用window.localStorage,它允许您将值永久保存在浏览器中,因此事件函数可以如下所示:

window.onload = function() {
  // 1 by default, in case there is nothing saved
  let selected = window.localStorage.getItem('selectedGraph') || 1;
  document.querySelector('#selGraph').selectedIndex = selected;
  graphUpdate();
}

那么graphUpdate函数应该包含一行来存储值:

function graphUpdate(){
    let value = document.querySelector('#selGraph');
    let graph = ["graph_1.gv", "graph_2.gv", "graph_3.gv", "graph_4.gv", "graph_5.gv"]
    render(graph[value.selectedIndex]);
    window.localStorage.setItem('selectedGraph', value.selectedIndex)
}

链接:https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

nfzehxib

nfzehxib2#

如果JS代码在文档元素存在之后运行(通过将<script>标记放在后面或使用defer),则可以简单地执行graphUpdate()函数。
要保存默认选项,我将使用localStorage
最后,不建议使用基于属性的事件侦听器,如onchangeonclick

<label for="alternativeGraph">Alternative graphs could be seen here:</label>
<select id="selGraph" aria-label="Graph">
  <!-- values are easier to work with than indexes -->
  <option value="graph_1.gv">Graph 1</option>
  <option value="graph_2.gv">Graph 2</option>
  <option value="graph_3.gv">Graph 3</option>
  <option value="graph_4.gv">Graph 4</option>
  <option value="graph_5.gv">Graph 5</option>
</select>
<button type="button" id="setDefaultGraphBtn">Change default graph</button>
// Constants
const DEFAULT_GRAPH_KEY = "default-graph";
const DEFAULT_GRAPH = "graph_1.gv";

// Elements
const graphSelect = document.getElementById("selGraph");
const btn = document.getElementById("setDefaultGraphBtn");

// Functions
const render = async (filename) => {
  const res = await fetch(filename);
  if (!res.ok) {
    throw new Error(`${filename}: ${res.status} ${res.statusText}`);
  }

  renderString(await res.text());
};

const graphUpdate = () => {
  render(graphSelect.value);
};

const setDefaultGraph = () => {
  const val = graphSelect.value;
  localStorage.setItem(DEFAULT_GRAPH_KEY, val);
  graphSelect.querySelectorAll("option").forEach((opt) => {
    // remove any previous "default" text
    opt.textContent = opt.textContent.replace(" (default)", "");
    // add "default" text
    if (opt.value === val) {
      opt.textContent += " (default)";
    }
  });
};

// Bind event listeners
graphSelect.addEventListener("change", graphUpdate);
btn.addEventListener("click", setDefaultGraph);

// Get localStorage value or default
const defaultGraph = localStorage.getItem(DEFAULT_GRAPH_KEY) ?? DEFAULT_GRAPH;

// set default selected
graphSelect.value = defaultGraph;

// Now run functions to initialise
setDefaultGraph();
graphUpdate();

相关问题