jQuery: Can't select just appended element

前端 未结 7 1617
天涯浪人
天涯浪人 2021-02-18 13:55

This is what happens on event:

$(\'div#pages\').append($(\'
...
\'));

And then, on another eve

7条回答
  •  既然无缘
    2021-02-18 14:29

    This happens to me a lot more often than I would like. I've tried just about everything and while some solutions work in certain scenarios or browsers, they don't work in others. Some of the most common solutions I've tried were:

    Waiting for DOM / element to be ready before selecting or manipulating it (this is so simple but actually works a lot of the time):

    $('#element').ready(() => {
        // Get or modify element
    });
    

    Using find (see CRABOLO's answer). Here is another example:

    // Create element
    let div = $('
    '); // Use element to find child let child = div.find('#element'); // Or let child = $('#element', div);

    If you're trying to listen to events triggered by an appended element, on should work for you most of the time since it can trigger for all future elements matching a selector (see Md Shahriar's answer). Here is another example:

    $(document).on('event', '.element', function() {
        // "event" has been triggered on a ".element"
    });
    

    And an example from the documentation:

    $("body").on("click", "p", function() {
        alert($(this).text());
    });
    

    If none of the other solutions work for you, you can always try to check manually using an Interval. This is the only way I've been able to solve this issue in certain situations:

    /* Usage:
       onEditable('#element', () => {
           // Element is now for sure ready to be selected or modified.
       });
    */
    function onEditable(selector, callback){
        if($(selector)[0]){
            callback();
            return;
        }
    
        let s = setInterval(() => {
            // Check if jQuery can find the element
            if($(selector)[0]){
                // Call callback function
                clearInterval(s);
                callback();
            }
        }, 20);
    }
    

    I can't stress this enough; if you can find another solution that works for you, use that instead, since this doesn't work based on events and takes up a lot more computer resources.

    Hope this helps someone having the same issues I did :).

提交回复
热议问题