通过使用.load()加载的文件访问已添加到DOM中的元素 [英] Accessing elements which have been added to the DOM via file loaded using .load()

查看:111
本文介绍了通过使用.load()加载的文件访问已添加到DOM中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery .load()加载php文件.这个php文件回显了一个新的div.该div包含一个属性"title",我需要在我的js文件中获取其值.

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

这将导致num ="undefined".我假设这样做的原因是,在执行初始$(document).ready之后,将div#max_page添加到DOM中,因此jQuery根本不知道它的存在.那正确吗?

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?

如何解决问题? (我尝试使用.live()进行实验,但无法使其对我有效)

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

推荐答案

当您检查num时,尚未将其添加到DOM中,因为ajax尚未完成将页面加载到DOM中的操作.在loadcomplete回调中执行此操作:

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

这篇关于通过使用.load()加载的文件访问已添加到DOM中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆