Jquery 从下拉列表中删除项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7018318/
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
Jquery remove item from dropdownlist
提问by JBone
jQuery(document).ready(function () {
$lstAccountType = $('select[id*="account_type"]');
$lstAccountType.change(function () {
$(this).remove('option[text="select one"]')
});
});
I want to remove the first element in my dropdown list when it is clicked. Does anyone have any pointers in regards to this?
我想在单击时删除下拉列表中的第一个元素。有没有人对此有任何指示?
回答by Adam Stacey
You should just be able to use:
您应该能够使用:
$lstAccountType.change(function () {
$lstAccountType.find("option[value='"+$lstAccountType.val()+"']").remove();
});
I haven't tested this, but have a go and let me know if it is any good or not?
我还没有测试过这个,但是试一试让我知道它是否有好处?
EDIT
编辑
If you only want to remove the first option each time you could try:
如果您只想在每次尝试时删除第一个选项:
$lstAccountType.change(function () {
if ($lstAccountType.find("option:first").attr("value") == $lstAccountType.val()) {
$lstAccountType.find("option[value='"+$lstAccountType.val()+"']").remove();
}
});
It needs some tidying up, but hopefully that might help.
它需要一些整理,但希望这可能会有所帮助。
EDIT
编辑
If you want to remove the first option only once you could do:
如果您只想删除第一个选项,您可以执行以下操作:
var first_option_removed = false;
$lstAccountType.change(function () {
if (!first_option_removed) {
if ($lstAccountType.find("option:first").attr("value") == $lstAccountType.val()) {
$lstAccountType.find("option[value='"+$lstAccountType.val()+"']").remove();
first_option_removed = true;
}
}
});
回答by numbers1311407
$(this).remove('option:first')
should do the trick, if you're sure you always want to remove the first.
应该可以解决问题,如果你确定你总是想删除第一个。
edit:
编辑:
$(this).remove('option:contains(select one)');
should do it on text.
应该在文本上做。
回答by Ali
Or if you want something easier to read, remember that you probably want to bind onFocus
since you want to remove the first list-item as soon as the select is clicked.
或者,如果您想要更容易阅读的内容,请记住您可能想要绑定,onFocus
因为您想在单击选择后立即删除第一个列表项。
$('#mySelectId').bind('focus' function(){
var listItems = $('#mySelect li');
if(listItems.length > 0){
$(listItems[0]).remove();
}
});