我有脚本,按键盘上的Enter键会隐藏$ this输入并生成带有该字段值的span。
$('.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);
});
答案 0 :(得分:1)
使用事件委托来动态创建dom
$(document).on('keypress','input','.form-control',function(e){
e.stopPropagation(); // stop the bubbling if it is there
alert("cal");
// do your work
});
注意:您创建了dom元素为div <div class="form-group work_experience">'+
,它是not input
字段
答案 1 :(得分:0)
试 改变
$('.work_experience .achievements').on('keypress','input', function(event)
到
$('.work_experience .achievements').live('keypress','input', function(event)