简体   繁体   English

如何获取在文档准备好后呈现的元素?

[英]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 .当我控制台 log active包含在文档准备好后呈现的元素的 id 时,它返回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.通过在done()函数内移动 click 事件处理程序,您将在该元素添加到 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. $.ajax是一个承诺,它们是异步的。 What you did is synchronous.你所做的是同步的。 done() is a callback called after $.ajax is done. done()是在$.ajax完成后调用的回调。 The code after $.ajax still proceeds even if $.ajax is not done yet.即使$.ajax尚未完成, $.ajax之后的代码仍会继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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