jquery 填充选择列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9998665/
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-27 11:31:26  来源:igfitidea点击:

jquery populate select list

jquery

提问by Nate Pet

I have this in my htm file

我的 htm 文件中有这个

    <select id="SelItem">

    </select>

Within my javascript file I have a section for jquery I have the following

在我的 javascript 文件中,我有一个 jquery 部分,我有以下内容

     var itemval= '<option value="OT">OT</option>';

     $("#SelItem").html(itemval);

Wouldn't the following populate my drop down with OT? It does not populate anything in the drop down

以下内容不会用 OT 填充我的下拉列表吗?它不会在下拉列表中填充任何内容

回答by Rion Williams

You might want to consider using append:

您可能需要考虑使用append

//Creates the item
var itemval= '<option value="OT">OT</option>';

//Appends it within your select element
$("#SelItem").append(itemval);?

Example

例子

Update

更新

As js1568 pointed out - the problem is most likely stemming from the page not being loaded when the JS / jQuery code is being executed. You should be able to fix this with the following:

正如 js1568 指出的那样 - 问题很可能是由于在执行 JS / jQuery 代码时没有加载页面。您应该可以通过以下方式解决此问题:

$(document).ready(function()
{
    //Creates the item
    var itemval= '<option value="OT">OT</option>';

    //Appends it within your select element
    $("#SelItem").append(itemval);?
});

回答by js1568

You need to wait until the page has loaded before running this code. Try wrapping your code inside $(document).ready()function.

在运行此代码之前,您需要等待页面加载完毕。尝试将您的代码包装在$(document).ready()函数中。

Introducing $(document).ready()

介绍 $(document).ready()

回答by Kristian

The problem is when the jquery is called, not what its doing.

问题是当 jquery 被调用时,而不是它在做什么。

$(document).ready(function() {
     var itemval= '<option value="OT">OT</option>';
     $("#SelItem").html(itemval);
});