简体   繁体   中英

How to get an element that rendered after document ready?

I have code like this:

// HTML
<div id="filter-option"></div>

//Javascript
$.ajax({
    method: "POST",
    url: "Some Url",
    data: {Some: "Data"}
}).done(funtion(msg){
    var result = JSON.parse(msg);
    renderFilterOption(result) // Some function to render elements to #filter-option
})

$("#myID").on('click', '.myClass', function(){
    var active = $("#ElementInFilterOption").attr("id");
    console.log(active);
})

When I console log active that contain and id of element that rendered after document ready, it return undefined . How to fix it?

Try like this:

// HTML
<div id="filter-option"></div>

//Javascript
$.ajax({
    method: "POST",
    url: "Some Url",
    data: {Some: "Data"}
}).done(funtion(msg){
    var result = JSON.parse(msg);
    renderFilterOption(result) // Some function to render elements to #filter-option

    $("#myID").on('click', '.myClass', function(){
        var active = $("#ElementInFilterOption").attr("id");
        console.log(active);
    })
})

By moving the click event handler inside the done() function, you will be adding the event handler to that element after it has been added to the DOM.

You should do this instead:

// Post request
$.ajax({
    method: "POST",
    url: "Some Url",
    data: {Some: "Data"}
}).done(funtion(msg){
    var result = JSON.parse(msg);
    renderFilterOption(result)
    $("#myID").on('click', '.myClass', function(){
        var active = $("#ElementInFilterOption").attr("id");
        console.log(active);
    })
})

$.ajax is a promise and they're asynchronous. What you did is synchronous. done() is a callback called after $.ajax is done. The code after $.ajax still proceeds even if $.ajax is not done yet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM