使用jQuery </option>动态创建<option>

时间:2009-09-07 08:51:27

标签: jquery option

我想在基于AJAX响应的盒子中动态构建s;即如果responseText为3,我想构建3个选项:

<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”部分:

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”:好吧,在这种情况下,我想填写一个简单的:

<option value="0">0<value>

我是JS的新手,不知道怎么做... 拜托,你能帮忙吗?

1 个答案:

答案 0 :(得分:4)

你可以这样做:

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));
    }
}

希望这有帮助。