繁体   English   中英

如何在页面加载时加载第一个下拉选项

[英]How to load first drop down option on pageload

我希望有一个列出不同鸟类的下拉菜单,并且希望每个选项显示该鸟类的唯一段落和图像。 下面的代码几乎对我有用,但是在页面加载时,我希望自动选择第一个选项。

  1. 我该怎么做呢?

  2. 这是解决此问题的最佳方法吗?

我对此并不陌生,任何帮助将不胜感激。 谢谢

https://jsfiddle.net/h0m0cpxk/

 <html> <body> <select id="opts" selected="selected" onchange="document.getElementById('ExtraInfo').firstChild.nodeValue = this.options[this.selectedIndex].getAttribute('extrainfo')"> <option value="buzzard" extrainfo="The buzzard is by far the most common of all our birds of prey, and its expansion has been dramatic">Buzzard</option> <option value="redkite" extrainfo="The red kite is a medium-large bird of prey in the family Accipitridae, which also includes many other diurnal raptors such as eagles, buzzards, and harriers">Red kite</option> <option value="sparrowhawk" extrainfo="Habitat and food availability remain the main limiting and controlling factors of sparrowhawk numbers">Sparrow hawk</option> </select> <div id="ExtraInfo">extra</div> </body> </html> 

一种简单的方法是默认情况下将第一个选项文本添加到ExtraInfo div中。 由于加载页面时会自动选择选择列表中的第一个选项,因此可以满足您的需求。

<div id="ExtraInfo">The buzzard is by far the most common of all our birds of prey, and its expansion has been dramatic</div>

第一个选项将被自动选择。 您可能不需要在此处触发更改事件。 您只需将第一段写成HTML的<p> 选择其他选项时,它将被覆盖。

另一种方法是在页面加载时通过Javascript触发onchange事件。 如果没有jQuery,这有点棘手,请参见以下问题:

https://stackoverflow.com/a/2856602/5742681

暂无
暂无

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

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