[英]Add and remove item dynamically in dropdown
How can I add or remove dropdown items dynamically in jQuery? 如何在jQuery中动态添加或删除下拉项? Below code is not working
下面的代码不起作用
$("#dropdownId").remove("<option value='12'>testing</option>");
$("#dropdownId").add("<option value='12'>testing</option>");
Can anyone suggest a way to do this? 有人可以建议一种方法吗?
To add elements, use .append()
: 要添加元素,请使用
.append()
:
$('#dropdownId').append('<option value="12">testing</option>')
or .appendTo()
: 或
.appendTo()
:
$('<option/>', { val: 12, text: 'testing' }).appendTo('#dropdownId');
To remove, use .remove()
differently: 要删除,请另外使用
.remove()
:
$('#dropdownId').find('option').filter(function ()
{
return this.value === '12' && $(this).text() === 'testing';
}).remove();
As a general recommendation, you should really read the API docs for simple jQuery questions like these. 作为一般建议,您应该阅读有关此类简单jQuery问题的API文档。 If you had read the documentation for
.add()
, for instance, you'd see that it does not do what you thought. 例如,如果您阅读了
.add()
的文档 ,您会发现它没有按照您的想法做。
Use a standard selector for the item you want to remove, rather than passing html markup: 对要删除的项目使用标准选择器,而不要传递html标记:
$('#dropdownId option[value="12"]').remove();
// or
$('#dropdownId').remove('option[value="12"]');
(I'm assuming you don't have more than one option with the same value.) (我假设您没有多个具有相同值的选项。)
The (approximate) opposite of .remove()
is .append()
: .remove()
的(近似)对角是.append()
:
$("#dropdownId").append("<option value='12'>testing</option>");
Remove: 去掉:
$("#selectList option[value='2']").remove();
Add: 加:
$('#selectList').append('<option>'+val+'</option>');
使用append
而不是add
!
add is not writing method. 添加不写方法。 use append() like,
像这样使用append(),
$("#dropdownId").append("<option value='12'>testing</option>");
here's some information from jQuery API: http://api.jquery.com/append/ 这是来自jQuery API的一些信息: http : //api.jquery.com/append/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.