gpt4 book ai didi

jQuery 不适用于动态创建的输入字段

转载 作者:行者123 更新时间:2023-11-28 01:42:44 24 4
gpt4 key购买 nike

我有脚本,在键盘上按下 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);
});

最佳答案

对动态创建的dom使用事件委托(delegate)

 $(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字段

关于jQuery 不适用于动态创建的输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24954363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com