我需要在某些情況下從選擇中刪除選項。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添加到選項標籤是非常罕見的。 –