jQuery with Bootstrap Modal ...
我正在动态创建信息框,并允许用户在输入文本框中键入框标题并在添加后清除输入...
第一次,它按预期工作..如果我尝试再创建一个盒子,之前创建的盒子标题也会改变...... :(
如何每次都创建一个包含唯一文本字段的框?
HTML
<div class="container wrapper">
<button type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#myModal">
<i class="glyphicon glyphicon-plus"></i> Add More
</button>
<div class="box-holder clearfix">
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<form role="form">
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-control" id="title">
</div>
<div class="form-group">
<label for="options">Options:</label>
<select id="mySelectOptions">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
<option>Option 5</option>
<option>Option 6</option>
</select>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="addBox" data-dismiss="modal">Add Box</button>
</div>
</div>
</div>
</div>
的jQuery
$(document).ready(function () {
$('#addBox').click(function () {
$( ".wrapper .box-holder" ).append( '<div class="new-box"><div><label class="box-title">Title: <span></span></label></div><div><label class="box-values">Values: <span></span></label></div></div>' );
var newTitle = $(".modal-body .form-group #title").val();
$(".new-box .box-title span").text(newTitle);
$(".modal-body .form-group #title").val('');
});
});
答案 0 :(得分:3)
这只是因为当你这样做时:
$(".new-box .box-title span").text(newTitle);
您定位与此选择器对应的每个html项目。而且这个选择器对于每个盒子都是一样的,所以你只需要改变它们。一个好的策略可能就是:
$('.new-box:last-of-type .box-title span').text(newTitle);
小提琴:https://jsfiddle.net/1ogee98n/
有关:last-of-type
选择器的详细信息,您可以在那里查看jQuery官方文档:https://api.jquery.com/last-of-type-selector/