Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

javascript - .focus() not firing for elements added to the DOM with JQuery


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Change this...

$('form :input').focus(function() {

To this...

$(document).on('focus', 'form :input', function() {

This will cause all future-created elements to retain that binding. These are called Delegated Event Handlers. The jQuery POD explains both the problem and the solution...

Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on(). To ensure the elements are present and can be selected, place scripts after the elements in the HTML markup or perform event binding inside a document ready handler. Alternatively, use delegated event handlers to attach event handlers....

The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready. (Source: jQuery on Handler Documentation.)

Full working demo with your code sample...

    $(document).ready(function(){

        var cont = 1;
        $( "#add-campo" ).click(function() {
            cont++;
            $( '<div class="form-group" id="campo'+cont+'"> <label>Campo: </label> <input type="text" name="titulo[]" placeholder="Digite aqui"> <button id="'+cont+'" class="btn-apagar"> - </button> </div>' ).appendTo( "#formulario" );
        });

        $(document).on('focus', 'form :input', function() {
            alert( "Handler for .focus() called." );
        });

        $( "form" ).on( "click", ".btn-apagar", function() {
            var button_id = $( this ).attr("id");

            $( '#campo' +button_id+'' ).remove();
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>ADICIONAR CAMPOS</h1>
<form id="add-pub" method="POST">
    <div id="formulario">
        <div class="form-group">
            <label>campo: </label>
            <input type="text" name="titulo[]" placeholder="Digite aqui">
            <button type="button" id="add-campo"> + </button>
        </div>
    </div>
    <div class="form-group">
        <input type="button" name="PubRot" id="PubRot" value="PUBLICAR">
    </div>
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...