Elements appended from AJAX call aren't accessible

前端 未结 3 2043
春和景丽
春和景丽 2021-01-28 13:07

I insert element from the php file as a result of successful ajax call. But for some reason that and everything in it is missing when I look at my source code of the page. It

相关标签:
3条回答
  • 2021-01-28 13:21

    Look at jQuery.on()

    Delegate the click event of your delete div Eg-

    $(document).on("click",".btn",function(){//bind click event for all .btn type
    alert("clicked");
    });
    

    DEMO

    0 讨论(0)
  • 2021-01-28 13:41

    You're most likely binding the click event handlers to your delete divs on document ready. When you add new divs, the click event handlers are not automatically bound to the new elements.

    So, after updating your data, bind the event handlers again, and you will be good to go.

    0 讨论(0)
  • 2021-01-28 13:47

    View Source in the browser only shows what was originally in the HTML of the page as originally downloaded from the server. It does not show content that was dynamically or programmatically added to the page.

    If you want to see the current content of the DOM, then use a DOM inspector as is built into nearly all browsers now. In Chrome, you can right-click, select "Inspect Element", click on the "Elements" tab and see the entire DOM hieararchy (you may need to expand the parts you want to see).


    When you say "isn't clickable", it isn't entirely clear what you mean. If you mean that your click handlers are not bound to the elements that were dynamically added to the page, that is likely to be expected because you probably ran some code that looks like this:

    $(some selector).click(function() {
        // code here
    });
    

    That code binds click handlers ONLY to the elements that exist at that moment, not to future elements that might match the selector.

    You can work-around that issue in one of several ways:

    1. You can manually bind events to the newly added elements.
    2. You can use delegated event handling (instead of static event handling) that will work with dynamically added elements.

    Dynamic event handling in jQuery works like this:

    $(some static parent selector).on("click", "selector that matches dynamic elements", fn);
    

    For example, this will work with dynamically added items in the #youtubeholder div that have a selector matching .deletevid:

    $("#youtubeholder").on("click", ".deletevid", function() {
        // delete element here
    });
    
    0 讨论(0)
提交回复
热议问题