我想在输入后添加一个新行。我的代码只能添加一次。请帮忙。
$(function () {
$('.items:last .item-quantity').keypress(function(e) {
var keyCode, path, duplicate;
keyCode = e.keyCode || e.which;
if(keyCode == '13') {
path = '.items:last';
duplicate = $(path).clone();
duplicate.children().val(null);
$(path).after(duplicate);
$(path + ' .item-name').focus();
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-12 items">
<input type="text" class="form-control item-name col-xs-2" placeholder="Name">
<input type="text" class="form-control item-quantity col-xs-2" placeholder="Quantity">
</div>
&#13;
答案 0 :(得分:3)
问题是,您只在页面加载时将keypress
事件侦听器附加到最后一个input
元素。你可以delegate the event处理一个共同的祖先元素,以便在新附加的元素上监听事件:
$(document).on('keypress', '.items:last .item-quantity', function(event) {
var keyCode = event.keyCode || event.which;
var path = '.items:last';
var $duplicate = $(path).clone();
if (keyCode === 13) {
$duplicate.children().val('');
$(path).after($duplicate);
$('.item-name', path).focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-12 items">
<input type="text" class="form-control item-name col-xs-2" placeholder="Name">
<input type="text" class="form-control item-quantity col-xs-2" placeholder="Quantity">
</div>
在上面的代码段中,事件侦听器被委托给document
对象。这意味着将对传播keypress
对象的所有document
事件进行检查。因此,如果您可以将事件侦听器直接附加到共同的祖先,那么效率会更高。
例如:
$('.parent-container').on('keypress', '.items:last .item-quantity', function(event) {
var keyCode = event.keyCode || event.which;
var path = '.items:last';
var $duplicate = $(path).clone();
if (keyCode === 13) {
$duplicate.find('input').val('');
$(path).after($duplicate);
$('.item-name', path).focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent-container">
<div class="col-xs-12 items">
<input type="text" class="form-control item-name col-xs-2" placeholder="Name">
<input type="text" class="form-control item-quantity col-xs-2" placeholder="Quantity">
</div>
</div>
答案 1 :(得分:1)
只需删除focus()
?
$(function () {
$('.items:last .item-quantity').keypress(function(e) {
var keyCode, path, duplicate;
keyCode = e.keyCode || e.which;
if(keyCode == '13') {
path = '.items:last';
duplicate = $(path).clone();
duplicate.children().val(null);
$(path).after(duplicate);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-12 items">
<input type="text" class="form-control item-name col-xs-2" placeholder="Name">
<input type="text" class="form-control item-quantity col-xs-2" placeholder="Quantity">
</div>