首页 > 解决方案 > 在 append() 中将 Javascript 变量传递给 HTML 代码

问题描述

我想将一个变量传递给我要附加的 html 代码:

var max = 1;    
$(wraper).on("click", ".add_field_button", function(e){ //on add input click
   e.preventDefault();
   if(max < max_fields){ //max input box allowed
     max++;
     console.log(max); // max now is equal to 2
     $(wrapper).append('<input id="street" name="street[{{$max}}]" class="form-control" type="text" placeholder="" value="">');
     }
})

而不是在输入的 html 代码中使用 $max 我想使用 max js 变量的值,这样我就可以获得 street[2]

我已经看到了许多关于如何仅将变量传递给 append() 的解决方案,而不是 HTML 代码中的变量......

标签: javascriptjqueryformsjquery-ui

解决方案


$(wrapper).append('<input id="street" name="street[' + max + ']" class="form-control" type="text" placeholder="" value="">');

或者

$(wrapper).append(concat('<input id="street" name="street[', max, ']" class="form-control" type="text" placeholder="" value="">'));

推荐阅读