创建< option>使用jQuery即时进行 [英] Create <option> on the fly with jQuery
本文介绍了创建< option>使用jQuery即时进行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据AJAX响应动态地在一个盒子中构建s;即,如果responseText为3,我想构建3个选项:
I'd like to build s on the fly in a box based on an AJAX response; i.e. if the responseText is 3, I'd like to build 3 options:
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
下面的代码正在工作:
$("#PAG_PLACEMENT").change(function(){
$.ajax({
type: "post",
url: "untitled.asp",
data: "iLanguage=1&iPlacement="+$("#PAG_PLACEMENT").val(),
success: function(responseText){
//alert(parseInt(responseText));
opts = parseInt(responseText);
var routeSelect = $("#PAG_POSITION").get(0);
routeSelect.options.length = 0; //reset to zero length
for(var i = 0; i < opts; ++i) {
routeSelect.options[i] = new Option(i+1,i+1);
}
}
});
});
但我想"jQueryfy"这部分:
but I'd like to "jQueryfy" the part:
var routeSelect = $("#PAG_POSITION").get(0);
routeSelect.options.length = 0; //reset to zero length
for(var i = 0; i < opts; ++i) {
routeSelect.options[i] = new Option(i+1,i+1);
}
更多,有时responseText为null(页面为空白),并且对其进行解析当然会给出一个"NaN":嗯,在这种情况下,我想用一个简单的填充:
More, sometimes the responseText is null (the page is blank) and parsing it gives of course a "NaN": well, in this case I'd like to fill the with a simple:
<option value="0">0<value>
我是JS新手,不知道该怎么做... 拜托,你能帮忙吗?
I'm a JS newbie and don't know how to do this... Please, can you help?
推荐答案
您可以这样做:
var routeSelect = $("#PAG_POSITION").get(0);
routeSelect.html(''); //clear-out options
if (isNaN(opts) || opts == 0) {
//Handles case where your response is invalid or zero
routeSelect.append($('<option/>').val(0).html(0));
} else {
//Add n items to the dropdown
for(var i = 0; i < opts; ++i) {
routeSelect.append($('<option/>').val(i).html(i));
}
}
希望这会有所帮助.
这篇关于创建< option>使用jQuery即时进行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文