简体   繁体   English

如何设置 select 选项等于 innerHTML

[英]How to set select option equal to innerHTML

I'm currently using flask to program this code.我目前正在使用 flask 来编写此代码。 My problem is I need to make the option value equal to the inner text of the option.我的问题是我需要使选项值等于选项的内部文本。

{% for symb in symbol %}
<script src="/static/script.js"></script>
<option id="options" value="0">{{ symb["symbol"] }}</option>
{% endfor %}

This is the code for the /static/script.js这是 /static/script.js 的代码

let option = document.querySelector('option').text;
changeContent(option);
function changeContent(option)
{
     var opt = document.querySelector('option').options[0];
     opt.value = option;
}

If I run the code, the option presents the actual text of {{ symb["symbol"] }}.如果我运行代码,该选项会显示 {{ symb["symbol"] }} 的实际文本。 However, it does copy it to the option value.但是,它确实将其复制到选项值。

Added this as an answer to update on the comment seen as it solved the issue and may help others将此添加为更新评论的答案,因为它解决了问题并可能对其他人有所帮助

You're approaching this the wrong way.你以错误的方式接近这个。 Rather than using JavaScript to do this render your template with the correct values to begin with而不是使用 JavaScript 来执行此操作,而是使用正确的值开始渲染您的模板

Also as it stands, you're including your script tag within your for loop.同样,您将脚本标签包含在 for 循环中。 This probably isn't what you want, so move it outside the for.这可能不是你想要的,所以把它移到 for 之外。

eg例如

<script src="/static/script.js"></script> 
{% for symb in symbol %} 

<option id="options" value="{{symb["symbol"]}}">{{ symb["symbol"] }}</option> 
{% endfor %} 

Apologies for the formatting I'm on mobile为我在移动设备上的格式道歉

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM