[英]Removing all values but the first from a drop down list using jQuery
if (questions[0]) {
$("select[id$=ddlPollQuestions] > option").remove();
$('#ddlPollQuestions').append('<option value="">Choose a question to compare to</option>');
$.each(questions, function(i, question) {
$('#ddlPollQuestions').append('<option value="' + question.QUESTIONID + '">' + question.TEXT + '</option>');
});
} else {
$("select[id$=ddlPollQuestions] > option").remove();
$('#ddlPollQuestions').append('<option value="' + 0 + '">' + 'There are no questions of this type' + '</option>');
}
它的作用是刪除所有以前的值,但我希望我的第一個選項,即“選擇一個問題......”保留,然后顯示“沒有問題......”作為我的第二個選項。 我的代碼沒有將“選擇一個問題..”作為第一個選項。 感謝您的關注!
更簡單的方法:
$('#ddlPollQuestions').children('option:not(:first)').remove();
使用:gt選擇器。
試試這個(注意我在每個循環之后的選項中添加了一個字符串變量 append 以獲得更好的性能):
if (questions[0]) {
$("select[id$=ddlPollQuestions] > option:gt(0)").remove();
$('#ddlPollQuestions').append('<option value="">Choose a question to compare to</option>');
var options = "";
$.each(questions, function(i, question) {
options += '<option value="' + question.QUESTIONID + '">' + question.TEXT + '</option>';
});
$('#ddlPollQuestions').append(options);
} else {
$("select[id$=ddlPollQuestions] > option:gt(0)").remove();
$('#ddlPollQuestions').append('<option value="' + 0 + '">' + 'There are no questions of this type' + '</option>');
}
由於您要刪除代碼中的所有選項,因此您可能只想在else
語句中再次選擇 append Choose a question...
if (questions[0]) {
$("select[id$=ddlPollQuestions] > option").remove();
$('#ddlPollQuestions').append('<option value="">Choose a question to compare to</option>');
$.each(questions, function(i, question) {
$('#ddlPollQuestions').append('<option value="' + question.QUESTIONID + '">' + question.TEXT + '</option>');
});
} else {
$("select[id$=ddlPollQuestions] > option").remove();
$('#ddlPollQuestions').append('<option value="">Choose a question to compare to</option>');
$('#ddlPollQuestions').append('<option value="' + 0 + '">' + 'There are no questions of this type' + '</option>');
}
例如: http://jsfiddle.net/xeYwv/2/
var $PollQuestions = $('#ddlPollQuestions');
if (questions[0]) {
$PollQuestions.children().remove();
$PollQuestions.append('<option value="0">Choose a question to compare to</option>');
$.each(questions, function(i, question) {
$PollQuestions.append('<option value="' + question.QUESTIONID + '">' + question.TEXT + '</option>');
});
} else {
$PollQuestions.children().remove();
$PollQuestions.append('<option value="' + 0 + '">' + 'There are no questions of this type' + '</option>');
}
你所擁有的已經非常接近了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.