Jquery 引导表单:如何动态创建单选按钮的唯一名称
这个问题是这个问题的后续问题 这说明了我想要实现的目标 最终版本由@Scaramouche提供Jquery 引导表单:如何动态创建单选按钮的唯一名称,jquery,vue.js,bootstrap-4,Jquery,Vue.js,Bootstrap 4,这个问题是这个问题的后续问题 这说明了我想要实现的目标 最终版本由@Scaramouche提供 下面的功能是动态地建立一个“列表”,其中包含四个一组的单选按钮 这些组中的每一个都应该有一个唯一的名称,这样可以选择其中一个选项,同时还可以在其他“组”中选择其他选项。这是一个挑战,因为这个“列表”是用引导表单构建的。如何动态创建这些名称?这可以通过Vue或JavaScript实现(没有首选项) HTML打开 诀窍是查找最后添加的.module。现在,使用.html()插入新字段,您没有这种包装sp
下面的功能是动态地建立一个“列表”,其中包含四个一组的单选按钮 这些组中的每一个都应该有一个唯一的名称,这样可以选择其中一个选项,同时还可以在其他“组”中选择其他选项。这是一个挑战,因为这个“列表”是用引导表单构建的。如何动态创建这些名称?这可以通过Vue或JavaScript实现(没有首选项) HTML打开
诀窍是查找最后添加的
.module
。现在,使用.html()
插入新字段,您没有这种包装span
。。。因此,请改用.clone()
。将新附加的标记作为目标将更容易
然后,使用变量计算单击事件。。。您可以创建唯一的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);
});
});
您的。使用计数器修改下一组的名称。还将.html()
更改为.clone()
,以处理整个元素的副本,而不仅仅是其内容
非常简洁易懂的解决方案!现在,新的div先来了,他们把其他div推到了最前面。我想在最后一个div之后再克隆一个div,所以第一个问题在上面!我该怎么做?@josefdev你有什么改变吗?每次添加span.module
时,它都会添加到末尾,就在选项标签的前面。我注意到的可能是欺骗你的是,作为第一个的克隆,它似乎与第一个具有相同的数据,这可能会造成它是第一个的印象,但事实并非如此,它们都是在最后添加的。试着在添加另一个之后更改输入的内容和每个新输入的收音机,你就会明白我的意思了。您可以通过每次创建新的span
时清理所有输入来解决此问题added@Scaramouce谢谢你给我指明了正确的方向!
$("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");
});
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);
});
});