简体   繁体   English

当页面使用JavaScript / jQuery加载时,如何获取选择框的第一个选项以自动显示在div中?

[英]How do I get the first option of a select box to display in a div automatically when the page loads with JavaScript/jQuery?

Here's the code that I have at the moment. 这是我目前拥有的代码。 How can I get Apple to print below the select box automatically when the page loads? 页面加载后,如何使Apple自动在选择框下方打印?

<script>
function getOption() {
    var obj = document.getElementById("mySelect");
    document.getElementById("demo").innerHTML = 
    obj.options[obj.selectedIndex].text;
}
</script>

<form>
Select your favorite fruit:
<select id="mySelect" onchange="getOption()">
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>
<br><br>
</form>

<p id="demo"></p>

It will be easier for you to use jquery. 使用jquery会更容易。 The code will be: 该代码将是:

$(document).ready(function(){
    var value = $("#mySelect option:first").val();
    $("#mySelect").after("<div>"+value +"</div>");
});

If you're not using jquery, you can try this: 如果您不使用jQuery,则可以尝试以下操作:

<script>
function getOption() {
    var obj = document.getElementById("mySelect");
    document.getElementById("demo").innerHTML = 
    obj.options[obj.selectedIndex].text;
}

document.addEventListener('DOMContentLoaded',function(){
    getOption();
});
</script>

It's just calling your function once the page has loaded. 页面加载后,它只是在调用您的函数。

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

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