Javascript 使用 Jquery 在组合框中动态添加选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6679134/
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
Add options dynamically in combo box using Jquery
提问by suganthar
When i add a new option to a DropDownList using jQuery, it is duplication the values whenever i use that dropdownlist.
当我使用 jQuery 向 DropDownList 添加新选项时,每当我使用该下拉列表时,它都会复制值。
For an example :
例如:
var myOptions = { val1 : 'Suganthar', val2 : 'Suganthar2'};
$.each(myOptions, function(val, text) {
$('#mySelect').append(new Option(text, val));
});
Suganthar, and Suganthar2 are duplicatiing values.
Suganthar 和 Suganthar2 是重复值。
Could anyone give me some idea to rectify this issue
谁能给我一些想法来纠正这个问题
回答by algiecas
Actually it should work, but you can try alternative way by using an array:
实际上它应该可以工作,但是您可以使用数组尝试替代方法:
var myOptions = [{ text: 'Suganthar', value: 1}, {text : 'Suganthar2', value: 2}];
$.each(myOptions, function(i, el)
{
$('#mySelect').append( new Option(el.text,el.value) );
});
回答by Pablo Fernandez
Your code works for me, see:
您的代码对我有用,请参阅:
Perhaps you're missing the $(document).ready
part and the select element is not present when the code runs?
也许您错过了该$(document).ready
部分并且在代码运行时不存在 select 元素?
回答by Suga
Thanks for your answers. My situation was different. It seems like
感谢您的回答。我的情况不同。这好像是
- There are two buttons which are Review the the statement and Retract the statement. In Both situations, im using same dialog box with which it contains particular combo box ( Suganthar and suganthar 2 are records)
- Firstly, when i click review the statement button, the dialog box will pop up wth tht combo box and those two records and then it works fine till the program end.
- Secondly, when i click retract the review button, the same dialog box will pop up with the combo box (suganthar, suganthar2, suganthar, suganthar 2 are repeating values)
- 有两个按钮,分别是查看语句和撤回语句。在这两种情况下,我都使用包含特定组合框的相同对话框(Suganthar 和 suganthar 2 是记录)
- 首先,当我单击查看语句按钮时,对话框会弹出带有组合框和那两个记录的对话框,然后它可以正常工作直到程序结束。
- 其次,当我单击撤回按钮时,将弹出相同的对话框和组合框(suganthar, suganthar2, suganthar, suganthar 2 are repeating values)
After a log search of this, i found and got a idea...
在对此进行日志搜索后,我发现并得到了一个想法......
var myOptions = [{ text: 'Suganthar', value: 1}, {text : 'Suganthar2', value: 2}];
**$('#mySelect').empty();**
$.each(myOptions, function(i, el)
{ $('#mySelect').append( new Option(el.text,el.value) );});
So we would have empty every time it works mate.
所以每次它工作时我们都会有空的。
Hope it will help when you get same problem. I really appreciate your quick response in answering the question. Once again. Thanks
希望当你遇到同样的问题时它会有所帮助。我非常感谢您在回答问题时的快速反应。再来一次。谢谢