【问题标题】:Keep option selected on page refresh在页面刷新时保持选择选项
【发布时间】:2017-12-14 22:50:01
【问题描述】:

那么我的代码是如何工作的,我会给你一个要点。 当 html_files 中没有文件时,默认选项是“---”,但是当 html_files 中存在文件时,现在有两个选项, 1) “---” 2)文件。但默认仍为“---”

所以我想做的是,当 html_files 中存在文件时,我希望将默认选项更改为当前文件,而不是“---”。我想不出办法来做到这一点。有人可以帮助我吗?

<span title="list resources who's involved etc">About File:
      <select class="experiment_file_selector" id="about_file" name="about_file">
        <option value="None" {% if not exp.about_file %}selected="selected"{% endif %}>---</option>
        {% for file in html_files %}
          <option value="{{ file.id }}" {% if file == exp.about_file %}selected="selected"{% endif %} >{{ file.get_base_name }}</option>
        {% endfor %}
      </select></span>

我按照下面的建议添加了一个 JS 脚本,当 exp.about_file 存在时,它可以在选择输入标签上获取默认文件,但要在模板上显示它需要手动单击。 为了自动化这个过程,我尝试使用 .click() 似乎以某种方式失败。

所以基本上它是如何工作的,我从选择列表“---”或 listFile[0] 中选择第一个选项,然后手动选择第二个 exp.about_file 或 listFile[1],它会提供一些结果如何,但它没有发生在 JS 脚本中。

所以有人可以建议我一种方法来自动化鼠标点击事件 listFile[0] 和 listFile[1],有点像我的 JS 代码,所以它可以工作。

谢谢

$(document).ready(function(){
  var listFile = document.getElementById('about_file');
  if (listFile.length > 1) 
  {
    listFile[1].setAttribute('selected', 'selected');
    listFile[0].click();
    listFile[1].click();
  }
});

【问题讨论】:

标签: javascript jquery django python-2.7 django-views


【解决方案1】:

如果你使用 javascript 会很容易。只需在页面加载时添加属性 selected="selected"。

document.addEventListener('DOMContentLoaded', function(e) {
  var listFile = document.getElementById('about_file');
  if (listFile.length > 1) {
    listFile[1].setAttribute('selected', 'selected');
  }
});

【讨论】:

  • 代码有效,它默认获取文件,但我担心的是文件实际上必须被单击并被选中并激活才能工作。我不知道为什么。我必须去选择选项,然后工作就完成了
  • 您可以使用.click()触发点击第一个选项(第一个文件),例如:listFile[1].click();记得在listFile[1].setAttribute('selected', 'selected');下方添加它
  • $(document).ready(function(){ var listFile = document.getElementById('about_file'); if (listFile.length > 1) { listFile[1].setAttribute('selected' , '选中'); listFile[0].click(); listFile[1].click(); } });不工作。你能帮忙吗
  • 我不知道“传递结果”代码是如何工作的,但是如果它在触发点击事件时没有运行,您可以用这些代码替换listFile[0].click();listFile[1].click();。我没有足够的信息,但是.. 无论如何,只要确保您的“交付”代码在 if (listFile.length &gt; 1) 中运行。
猜你喜欢
  • 2020-08-30
  • 2014-03-26
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 2017-07-09
相关资源
最近更新 更多