Html Onload 事件在选择框(下拉列表框)中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30890250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:39:38  来源:igfitidea点击:

Onload event not working in select box (Dropdown List Box)

htmlcss

提问by Vijayakumar B

JSFIDDLE Link for Reference

JSFIDDLE 参考链接

<script>
.greenText{ color:green; }
</script>

<html>
<select onload="this.className='greenText'" onchange="this.className='greenText'">
    <option value="apple" >Apple</option>
    <option value="banana" >Banana</option>
    <option value="grape" >Grape</option>
</select>
</html>

In the above example i add the CSS class for both onload and onchange event. But here only works on onchange but not working in onload event. I want to be in green color at the time of loading 'Dropdown Box'.

在上面的例子中,我为 onload 和 onchange 事件添加了 CSS 类。但这里只适用于 onchange 而不适用于 onload 事件。我想在加载“下拉框”时为绿色。

回答by Federico

"Select" does not support the "onload" event. Try this

“Select”不支持“onload”事件。尝试这个

<style type="text/css">
.greenText{ color:green; }
</style>

<script type="text/javascript">
window.addEventListener("load",function(){
    document.getElementById("my_select").className="greenText";
},false);
</script>

<select id="my_select" onchange="this.className='greenText'">
    <option value="apple" >Apple</option>
    <option value="banana" >Banana</option>
    <option value="grape" >Grape</option>
</select>

回答by Quentin

A select element doesn't load any external content, so there is no load event.

select 元素不会加载任何外部内容,因此没有加载事件。

If you want to fire JS on it immediately after it has been added to the DOM, just put a <script>element after its end tag.

如果您想在将其添加到 DOM 后立即在其上触发 JS,只需<script>在其结束标记后放置一个元素即可。

It would seem to make more sense to simply use a classattribute instead of involve JS though.

不过,简单地使用class属性而不是涉及 JS似乎更有意义。

回答by Bob Tate

since you just want it to be green regardless (onload or onchange) just need to set the class on the select.

因为你只希望它是绿色的(onload 或 onchange)只需要在选择上设置类。

<select class='greenText'>
    <option value="apple" >Apple</option>
    <option value="banana" >Banana</option>
    <option value="grape" >Grape</option>
</select>