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

标签 jquery html forms input

我有一个脚本,按键盘上的 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/

相关文章:

C# - 将焦点传递给 tabcontrol/页面并且无法滚动鼠标滚轮

javascript - 如何使用 jquery 生成和附加一个随机字符串

html - 快速4错误: load html string to webview

Javascript 图片上传和调整大小问题

html - 文本无边框的左面板

javascript - 按 Enter 键时禁用以 html 格式提交表单

python - Crispy 表单中的水平 View 和提交按钮不起作用

javascript - 浏览器可以对 XSS jquery.getJSON() 请求 header 中指定的 Set-Cookie 使用react吗?

Jquery比较同一类中的每三个div

javascript - 用于否定父元素中特定 HTML 元素的 JQuery 选择器