简体   繁体   English

如何使用JavaScript函数获取HTML值

[英]How to get an HTML value using a JavaScript function

I would like to set the value of a select-menu option to a value of a JavaScript object. 我想将选择菜单选项的值设置为JavaScript对象的值。

HTML 的HTML

<select id="eRedList">
    <option value=electroSeries.Li.potential>Li</option>
</select>

JS JS

var electroSeries = {
    Li: {name : "Li", charge : "1", potential : -3.05, redReaction : "Li+(aq) + e- >> Li(s)", oxReaction : "Li(s) >> Li+(aq) + e-"};
}

so here, I want to the value associated with the property 'potential' to the HTML value. 所以在这里,我想将与属性“ potential”关联的值转换为HTML值。 However, when I try to display this in a text box just to see what I get, I end up getting 'electroSeries.Li.potential' written instead of the numerical value. 但是,当我尝试在文本框中显示此内容以查看得到的内容时,最终得到的是“ electroSeries.Li.potential”而不是数值。

I'm relatively new to JS, so any help would be appreciated! 我是JS的新手,所以我们将不胜感激!

Html and js cannot interact like you expect without an external library (like angular). HTML和js在没有外部库(例如angular)的情况下无法像您期望的那样进行交互。 You need to access your option element from the javascript and apply the value: 您需要从javascript访问option元素并应用值:

var electroSeries = {
    Li: {name : "Li", charge : "1", potential : -3.05, 
         redReaction : "Li+(aq) + e- >> Li(s)", 
         oxReaction : "Li(s) >> Li+(aq) + e-"};
}
var select = document.getElementById('eRedList');
select.options[0].value = electroSeries.Li.potential;

Edit: Solution based on comments 编辑:基于评论的解决方案

 var electroSeries = { Li: { potential : -3.05 }, K: { potential : -2.92 }, Ca: { potential : -2.76 }, }; var select = document.getElementById('eRedList'); for(var i in electroSeries) { var option = document.createElement('option'); option.innerHTML = i; option.name = i; option.value = electroSeries[i].potential; select.appendChild(option); } 
 Element: <select id="eRedList"></select> 

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

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