我需要在某些情况下从选择中删除选项。javascript/jquery从选择中删除或删除选项
基本上是:
if(mystatement == true)
{
//remove item with id 'option1' from select of id 'select1'
}
任何人都知道的代码为我做到这一点?
非常感谢。
我需要在某些情况下从选择中删除选项。javascript/jquery从选择中删除或删除选项
基本上是:
if(mystatement == true)
{
//remove item with id 'option1' from select of id 'select1'
}
任何人都知道的代码为我做到这一点?
非常感谢。
编辑
由于id是文件没有必要把它与父选择元素中是独一无二的。你可以做简单的
$("#option1").remove();
的jQuery:
$("#option1").remove();
或
$("#select").remove("#option1");
与经典的JavaScript方法:
var option1 = document.getElementById("option1");
document.getElementById("select1").removeChild(option1);
按值删除:
$("#select1 option[value=1]").remove();
消除由文字:
$("#select1 option:contains(Text)").remove();
对于文本来说,'contains'似乎是一个糟糕的主意,不是吗?为什么不使用'$(“#select1选项:[text ='我的文字']”)'? –
我见过很多人有这个问题。我已经创建了这个可能有用的脚本。希望你喜欢它:
var robable = {
init: function() {
robable.get_selected_option_from_select();
},
get_selected_option_from_select: function() {
$(".robable").off().on("change", function() {
if ($(this).val() !== "") {
robable.add_to_list($(this));
}
});
},
remove_option_from_select: function(select_id, value) {
$("#" + select_id + " option[value='" + value + "']").remove();
},
add_option_to_select: function(select_id, value, text) {
$('#' + select_id).append('<option value="' + value + '">' + text + '</option>');
},
add_to_list: function(select) {
option_text = $(".robable option[value='" + select.val() + "']").text();
//Add to list
$('#list').append("<li data-value='" + select.val() + "' data-text='" + option_text + "'><a href='#' class='filter-remove' data-parent-id='" + select.attr("id") + "'>Delete</a> " + option_text + "</li>");
robable.remove_from_list();
//Remove from select
robable.remove_option_from_select(select.attr("id"), select.val());
},
remove_from_list: function() {
$(".filter-remove").off().on("click", function() {
var select_id = $(this).data('parent-id');
var option_value = $(this).closest("li").data('value');
var option_text = $(this).closest("li").data('text');
//Add to select
robable.add_option_to_select(select_id, option_value, option_text);
//Remove from list
$(this).closest("li").remove();
});
}
};
robable.init();
<!DOCTYPE html>
<html>
<head>
<title>Select Robables</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<ul id="list"></ul>
</body>
</html>
'$( “#选择1”)'是不必要的。 '$(“#option1”)。remove()'就足够了,因为它与'id'匹配。 –
@Marko:当您发表评论时,我正在编辑它:-)我离开了原文,因为将ID添加到选项标签是非常罕见的。 –