动态创建的表单取决于<select>不起作用



我正在开发一个网站,该网站必须根据用户选择的值(<select>)显示各种产品的特定表单 - 因此通过javascript函数(buildform())在循环中动态创建许多各种表单。代码不起作用,例如,表单未创建/附加到包装器。我缩小了问题的范围,我认为问题与jquery选择器/div-id (#ecorpproductwrapper"+ecorp_eprodselectid)的不同值有关。当我使用(仅作为测试)#ecorpproductwrapper"(没有变量ecorp_eprodselectid;另请参阅下面的代码中的替代作品)时,代码工作正常,例如表单已构建。我通过控制台检查了div-id 和 jquery 选择器的ecorpproductwrapper"+ecorp_eprodselectid值是否相同,所以我不明白出了什么问题?

请参阅下面的简化代码:

for(var i=0;i<5;i==){
  var ecorp_eprodselectid; //will have various values
  //function to build form depending on selected value in <select class= eprodtype"+ecorp_eprodselectid >
  $(".eprodtype"+ecorp_eprodselectid).focus(function () {
    var previous;
    // Store the current value on focus and on change
    previous = this.value; //old select value
   }).change(function() {
    var optionsform = buildform(this.value);
    console.log('append form'+optionsform);
    //NEXT 2 lines doe NOT WORK
    $("#ecorpproductwrapper"+ecorp_eprodselectid).children().remove(); //remove previous form
    $("#ecorpproductwrapper"+ecorp_eprodselectid).append(optionsform);
    //ALTERNATIVE works: $('#ecorpproductwrapper').children().remove(); //remove previous tariif struct form
    //ALTERNATIVE works: $('#ecorpproductwrapper').append(optionsform);
    var str = "#ecorpproductwrapper"+ecorp_eprodselectid;
    console.log('STRING ECORP PRODUCT APPEND: '+str);
    console.log('change eprod val: '+this.value);
    previous = this.value;
  });//$("").focus(function () {
}//for i
//function to build form
var buildform = function(ecorp_eproductid) {
//some code here
//NEXT LINE does not work:
   form += '<td> <div id="ecorpproductwrapper'+ ecorp_eprodselectid+'"> </div>  </td> </tr>'; //cell with wrapper for ecorp product info
   //ALTERNATIVE WORKS: form += '<td> <div id="ecorpproductwrapper"> </div>  </td> </tr>'; //cell with wrapper for ecorp product info
  //some code here; returns form
  }//function buildform

我想你忘了在你的函数中添加ecorp_eprodselectid。

var buildform = function(ecorp_eprodselectid ) {

关于上面给定的文本,我们假设的几件事:

  • 你知道这个.value有效
  • 控制台.log显示选项表单具有它应该具有的 HTML。OP中没有说,但如果没有,该功能不起作用。函数似乎已经丢失了var buildform = function(someVar)正如 buysDB 所指出的那样

由于我看不到您的代码,我将首先尝试通过追逐以下内容来清除所有内容:

$("#ecorpproductwrapper"+ecorp_eprodselectid).children().remove();

自:

$("#ecorpproductwrapper"+ecorp_eprodselectid).html("");

然后:

$("#ecorpproductwrapper"+ecorp_eprodselectid).html(optionsform);

如果您无意在 DIV 中保留任何内容,则无需追加。

如果 (#ecorpproductwrapper"+ecorp_eprodselectid) 中也有文本,这就是使用 children() 的原因,请考虑选择可以清除的 DIV。

如果这仍然不起作用,则遗漏了一些需要考虑的内容。

最新更新