Accessing elements which have been added to the DO

2019-07-27 21:41发布

I am using jQuery .load() to load a php-file. This php-file echos out a new div. This div contains an attribute "title", whose value I need to get in my js-file.

// file.php
echo '<div id="max_page" title="' . $max_page . '"></div>';

// js
$("someElement").load("file.php");
var num = $("div#max_page").attr("title");

This results in num = "undefined". I am assuming the reason for this is that the div#max_page gets added to the DOM after the initial $(document).ready was performed and hence jQuery simply doesn't know of its existence. Is that right?

How can the problem be solved? (I tried experimenting with .live() but couldn't get it to work for me)

3条回答
Animai°情兽
2楼-- · 2019-07-27 21:53

When you check the num it hasn't been added to the DOM yet as the ajax hasn't finished loading the page into the DOM yet. Do it in the complete callback of load:

$("someElement").load("file.php",function(){
var num = $("div#max_page").attr("title");
});
查看更多
做个烂人
3楼-- · 2019-07-27 21:57

You're right on thinking that your timing is wrong :)

// js
$("someElement").load("file.php", function(){
    var num = $("div#max_page").attr("title");
    // here you can do with num whatever you need
});

The function passed as a second argument will be executed immediately after file.php is loaded into someElement, thus guaranteed that the title attribute will exist at this point.

查看更多
祖国的老花朵
4楼-- · 2019-07-27 22:03

the file hasn't loaded when you set num. use a callback.

$("someElement").load("file.php", function () {
   var num = $("div#max_page").attr("title");
});
查看更多
登录 后发表回答