【发布时间】:2014-07-25 11:07:13
【问题描述】:
我有脚本,按键盘上的 Enter 键会隐藏 $this 输入并生成包含该字段值的跨度以显示。
$('.work_experience .achievements').on('keypress','input', function(event){
if (!$(this).val() && event.which == 13 ) {
alert('Input something');
event.preventDefault();
}
else if (event.which == 13) {
event.preventDefault();
var value = $(this).val();
$(this).parent().append('<span><i class="fa fa-times"></i> ' + value + '</span><input type="text" class="form-control input-xs" placeholder="I did" autofocus>');
$(this).css('display', 'none');
$('.achievements input:last-child').focus();
}
});
它有效。但是然后我有按钮,单击它会生成新的输入字段。并且,新创建的输入,脚本不再起作用。感谢您的帮助。
PS添加新字段集的脚本
$('.form_fields').on('click','#add_work', function(event){
event.preventDefault();
var field_set = '<div class="form-group work_experience">'+
'<input type="text" class="form-control input-m" id="company_name" placeholder="Company name">'+
'<input type="text" class="form-control input-m" id="company_place" placeholder="Company location">'+
'<input type="text" class="form-control input-m" id="work_period_start" placeholder="Beginnig">'+
'<input type="text" class="form-control input-m" id="work_period_end" placeholder="End">'+
'<label><input type="checkbox"> Currently</label>'+
'<textarea class="form-control" rows="5" placeholder="Write a few sentences about that company"></textarea>'+
'<input type="text" class="form-control input-m" placeholder="Your position">'+
'<label><strong>Achievements</strong></label>'+
'<div class="achievements">'+
'<input type="text" class="form-control input-xs" placeholder="I did">'+
'</div>'+
'</div>';
$(this).prev().after(field_set);
});
【问题讨论】:
-
你使用的jquery版本?
-
因为您将其附加到
$(this).parent(),但委托处理程序附加到$(this)而不是其父级。因此新添加的输入被放置在处理程序的监控范围之外 -
@Banana 能否详细说明一下,谢谢
-
@Elangovan 控制台没有错误
-
@SergeyDubovik 是的,我会把它作为答案发布,因为它很长