使用 JQuery 向下拉 <select> 框添加值

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

Adding values to a dropdown <select> box using JQuery

jquery

提问by Elitmiar

I have a issue with populating values in a box using JQuery.

我在使用 JQuery 在框中填充值时遇到问题。

Instead of adding it underneath each other it adds it next to all other elements

它不是将其添加到彼此下方,而是将其添加到所有其他元素旁边

my code

我的代码

$('#pages option').append($('#t1').val());

回答by Russ Cam

I think you want

我想你想要

$('#pages').append($('#t1').val());

assuming pages is the id of your <select>. Also, $('#t1').val()should be an <option>element, not a value. Something like this

假设 pages 是您的<select>. 此外,$('#t1').val()应该是一个<option>元素,而不是一个值。像这样的东西

 var newOption = $('<option value="'+val+'">'+val+'</option>');
 $('#pages').append(newOption);

or

或者

var newOption = $('<option>');
newOption.attr('value',val).text(val);
 $('#pages').append(newOption);

whichever is easier for you to read.

哪个对你来说更容易阅读。

Here's a Working Demo

这是一个工作演示

回答by peirix

You probably want something along the lines of

你可能想要一些类似的东西

$("#pages").append("<option>"+$("#t1").val()+"</option>");

That will make and append an option to your select box

这将制作并附加一个选项到您的选择框

回答by chopss

Try this..

尝试这个..

using jquery you can use

使用 jquery 你可以使用

  this.$('select#myid').append('<option>newvalue</option>');

where "myid" is the idof the dropdown list and newvalueis the text that you want to insert..

其中“ myid”是下拉列表的ID,而newvalue是您要插入的文本。