我正在开发一个网页,它首先创建了一些选择表单。当用户为特定的选择表单选择一个选项时,会根据用户的选择创建另一个子表单,并将其附加到该选择表单。不幸的是,我的代码不起作用,例如,(1) 未创建子表单和 (2) 用于附加子表单的选择器未正确编码 - 它们始终指向固定值 (#wrapper-options3)。我的原始代码更复杂,但我在下面的代码中复制了结构+一些简单的示例函数 - 它会导致与原始代码相同的错误。我应该如何正确编码子表单的添加(在下面代码的第 2 步中)?例如,如何为#wrapper-options 获取正确的选择器值?
<script>
$(document).ready(function(){
var previous;
//functions
var Buildform = function(i){
var form;
form = '<select class="eprodtype'+i+'" name="transport'+i+'">';
form += '<option value="bike"> Bike'+i+' </option>';
form += '<option value="car"> Car'+i+' </option>';
form += '</select>';
form += '<div id="wrapper-options'+i+'"> "wrapper-options'+i+'" </div>';
return $(form);
}//Buildform
var Buildsubform = function(i){ //i will contain <select> value
var subform = '<p> '+i+' </p>';
console.log('Buildsubform():'+subform);
return $(subform);
}
//step 1: build 'base' form with multiple select forms
for(var i=0;i<3;i++){
var form = Buildform(i);
$('#wrapper').append(form);
}
//step 2: build subform depending on choice user within base form
for(var i=0;i<3;i++){
$(".eprodtype"+i).focus(function () {
// Store the current value on focus and on change
var previous = this.value; //old select value
}).change(function() {
var subform = Buildsubform(this.value);
console.log('append subform'+subform);
//ERROR IN THE NEXT 2 LINES; selector '#wrapper-options'+i always has a value #wrapper-options3 - instead of a dynamic value
$('#wrapper-options'+i).html(''); //remove previous subform
$('#wrapper-options'+i).html(subform);
var str = '#wrapper-options'+i;
console.log('wrapper-options val: '+str);
console.log('change eprod val: '+this.value);
previous = this.value;
});
}//for i
}); //$(document).ready
</script>
</head>
<body>
<form>
<div id="wrapper"></div> <!--wrapper for function Buildform() -->
</form>
</body>