如何为输入占位符,输入ID和跨文本动态添加的行增加1个数字?
我能够获得下一个数字,但没有获得增量值。
HTML:
<a href="#" class="btn btn-vote" id="addOption"><i class="glyphicon glyphicon-plus"></i> Add Option</a>
<div class="poll-options">
<ul>
<li><span class="po-number">1</span><input type="text" class="form-control" id="pollOption-1" placeholder="Option 1"></li>
<li><span class="po-number">2</span><input type="text" class="form-control" id="pollOption-2" placeholder="Option 2"></li>
</ul>
</div>
jQuery的:
$("#addOption").click(function () {
var optionCounter = 2;
var qOption = '<li><span class="po-number">'+optionCounter+'</span><input type="text" class="form-control" id="pollOption-'+ optionCounter +' " placeholder="Option '+ optionCounter +' "><i class="fa fa-times remove-this"></i></li>';
$(".poll-options ul").append(qOption);
optionCounter++;
});
$(".poll-options").on("click", ".remove-this", function() {
$(this).closest("li").remove();
});
答案 0 :(得分:2)
您可以使用data-attribute
,并获取最新的元素属性并将其递增,这样可以避免重复,并允许您在删除时重新编号。
代码:
$("#addOption").click(function () {
var num = parseInt($('.po-number:last').attr('data-num'))+1;
var qOption = '<li><span class="po-number" data-num="'+num+'">'+num+'</span><input type="text" class="form-control" id="pollOption-'+ num +' " placeholder="Option '+ num +' "><i class="fa fa-times remove-this"></i></li>';
$(".poll-options ul").append(qOption);
});
删除和编号:
$(".poll-options").on("click", ".remove-this", function() {
$(this).closest("li").nextUntil().each(function(i,e){
var num = parseInt($(this).find("span").attr('data-num'))-1;
$(this).find("span").attr("data-num", num).text(num);
$(this).find("input").attr("id", "pollOption-"+num).attr("placeholder","Option "+num);
});
$(this).closest("li").remove();
});
代码使用nextUntil
来获取以下所有兄弟元素并相应地重新编号。
答案 1 :(得分:1)
您不需要在这里设置专门的计数器,只需计算ul
元素的子项:
$("#addOption").click(function () {
var id = $(".poll-options ul").children().length + 1;
if (id > 5) {
return; // 5 is maximum
}
var qOption = '<li><span class="po-number">'+ id +'</span><input type="text" class="form-control" id="pollOption-'+ id +'" placeholder="Option '+ id +' "><i class="fa fa-times remove-this"></i></li>';
$(".poll-options ul").append(qOption);
});
答案 2 :(得分:0)
将您的optionCounter
更改为全局变量,如下所示:
$(document).ready(function(){
optionCounter = 3;
});
$("#addOption").click(function () {
var qOption = '<li><span class="po-number">'+optionCounter+'</span><input type="text" class="form-control" id="pollOption-'+ optionCounter +' " placeholder="Option '+ optionCounter +' "><i class="fa fa-times remove-this"></i></li>';
$(".poll-options ul").append(qOption);
optionCounter++;
});
$(".poll-options").on("click", ".remove-this", function() {
$(this).closest("li").remove();
});