Accessing elements which have been added to the DOM via file loaded using .load()

岁酱吖の 提交于 2020-01-05 07:24:27

问题


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


来源:https://stackoverflow.com/questions/6401851/accessing-elements-which-have-been-added-to-the-dom-via-file-loaded-using-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!