灵感来自 Chrome Postman extension ,我想通过在导航到某个字段时自动添加新的输入字段并将焦点集中到新字段来实现多字段表单部分。下面的屏幕截图显示了 Postman 中的工作原理;最下面的行包含几个输入,当导航到这些输入时,会在其上方添加一个新行,可以在其中输入内容。
如何在 JavaScript/jQuery 中实现此行为?为了简化问题,我每行只需要一个输入字段。我创建了一个fiddle这应该作为解决方案的起点。
示例 HTML:
<div id="last-row">
<input name="multifield" placeholder="Value"></input>
</div>
最佳答案
看看我会怎么做:http://jsfiddle.net/jCMc8/8/
html:
<section>
<div id="initRow">
<input name="multifield" placeholder="Value">
</div>
</section>
JavaScript:
function addRow(section, initRow) {
var newRow = initRow.clone().removeAttr('id').addClass('new').insertBefore(initRow),
deleteRow = $('<a class="rowDelete"><img src="http://i.imgur.com/ZSoHl.png"></a>');
newRow
.append(deleteRow)
.on('click', 'a.rowDelete', function() {
removeRow(newRow);
})
.slideDown(300, function() {
$(this)
.find('input').focus();
})
}
function removeRow(newRow) {
newRow
.slideUp(200, function() {
$(this)
.next('div:not(#initRow)')
.find('input').focus()
.end()
.end()
.remove();
});
}
$(function () {
var initRow = $('#initRow'),
section = initRow.parent('section');
initRow.on('focus', 'input', function() {
addRow(section, initRow);
});
});
关于javascript - 当导航到某个输入字段时,如何自动生成新的输入字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13800298/