我有一个附加选择框的功能,可以选择生日日期。实现这一目标的最佳方法是什么?
当我运行该脚本时,在关闭选择之后添加for循环内的追加。追加是否有任何逻辑,还是不严格?我认为forloop必须在它继续之前完成。
function addChildOption(){
if (counterOption < 3) {
$("#add-child").append("<select name=\"child" + counterOption + "\" form=\"register\">");
for(var i = year-15; i > 1900 ; i--){
$("#add-child").append("<option class=\"choose-year\" value=" + i + ">" + i + "</option>");
}
$("#add-child").append("</select>");
}
}
结果:
<select form="register" name="child1"></select>
<option class="choose-year" value="1999">1999</option>
<option class="choose-year" value="1998">1998</option>
<option class="choose-year" value="1997">1997</option>
etc....
答案 0 :(得分:1)
您可以构造select
,将选项添加到该变量,然后将其附加到实际表单:
var sel = $('<select name="child' + counterOption + '" form="register" />');
for(var i = year-15; i > 1900; i--) {
sel.append($('<option value="' + i + '" class="choose-year">' + i+ '</option>'));
}
$('#add-child').append(sel);
答案 1 :(得分:1)
function addChildOption(){
if (counterOption < 3) {
var html = "<select name=\"child" + counterOption + "\" form=\"register\">");
for(var i = year-15; i > 1900 ; i--){
html += "<option class=\"choose-year\" value=" + i + ">" + i + "</option>");
}
html += "</select>"
$("#add-child").append(html);
}
}
答案 2 :(得分:1)
就我而言,我更喜欢做这样的事情:
function addChildOption() {
if (counterOption < 3) {
var addChild = $("#add-child");
var mySelect = $("<select />").prop("name", "child" + counterOption).prop("form", "register").appendTo(addChild);
for (var i = year - 15; i > 1900; i--) {
$("<option />").addClass("choose-year").prop("value", i).text(i).appendTo(mySelect);
}
}
}
就像那样,我直接将select添加到容器中,然后将选项添加到select。
答案 3 :(得分:1)
function addChildOption(){
if (counterOption < 3)
{
$("#add-child").append("<select name=\"child" + counterOption + "\" form=\"register\"></select>").queue(function(next){
for(var i = year-15; i > 1900 ; i--) {
$(this).children().append("<option class=\"choose-year\" value=" + i + ">" + i + " </option>");
}
next();
});
}
}