Bootstrap表单:如何为单选按钮动态创建唯一名称

这个问题是对这个问题的后续问题。

这个JSfiddle举例说明了我想要实现的目标。

最终解决方案由@Scaramouche提供

下面的function是动态建立一个“列表”,其中包含四个一组的单选按钮。

这些组中的每一个都应具有唯一的名称,这使得可以选择其中一个选项,同时仍然可以在其他“组”中选择其他选项。 这是一个挑战,因为这个“列表”是用Bootstrapforms构建的。 我该怎么做,动态创建这些名称? 这可以使用Vue或JavaScript(没有首选项)来完成。

JSfiddle上的 HTML


JavaScript的

 $("body").on('click', '#radioAddQuestion', function () { let singleQuestionModule = "singleQuestionModule"; let question = $(".module:first").html(); let question_label = $(".question-label:first").html(); $(question_label).insertBefore(".options-label"); $(question).insertBefore(".options-label"); }); 

使用计数器修改下一组的名称。 .clone() .html()更改为.clone()以使用整个元素的副本而不仅仅是其内容。

https://jsfiddle.net/DTcHh/60016/

诀窍是寻找最后添加的.module 。 现在,使用.html()插入新字段,你没有这个包装span ……所以请改用.clone() 。 定位新添加的标记会更容易。

然后,使用变量来计算click事件…您可以创建唯一id

 var n=0; $("body").on('click', '#radioAddQuestion', function () { // Counter. n++; var singleQuestionModule = "singleQuestionModule"; var question = $(".module:first").clone(); var question_label = $(".question-label:first").html(); $(question_label).insertBefore(".options-label"); console.log(question_label); // Undefined in this example... $(question).insertBefore(".options-label"); console.log(question.html()); // Add "_" and a number to the ids. $(document).find(".module:last").find("input[type='radio']").each(function(){ $(this).attr("id",$(this).attr("id")+"_"+n); }); }); 

你更新的小提琴 。