Accessing elements which have been added to the DO

2019-07-27 22:07发布

问题:

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)

回答1:

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");
});


回答2:

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.



回答3:

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

$("someElement").load("file.php", function () {
   var num = $("div#max_page").attr("title");
});