简体   繁体   English

使用jquery加载外部文件,然后引用它

[英]loading external file using jquery and then making reference to it

I have a js file that loads some content (external html file) into the DOM and then alerts the content that was just loaded 我有一个js文件,它将一些内容(外部html文件)加载到DOM中,然后警告刚刚加载的内容

boo.html boo.html

<div id="tyler">
   Tyler
</div>

play.js play.js

$('#result').load('../html/boo.html');
var mike = $('#tyler').text();
alert(mike);

file.html file.html

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>A</title>

    </head>
    <body>
        <div id="result"></div>
        <script type="text/javascript" src="play.js">
    </body>
</html>

For some strange reason when I alert(mike) What I get is blank. 出于某些奇怪的原因,当我alert(mike)我得到的是空白。 Cant you append a div with some id and then later reference the new div that you just injected? 你不能附加一个带有一些id的div然后引用你刚注入的新div吗?

在此输入图像描述

.load() is asynchronous. .load()是异步的。 It goes off and does its thing and your code keeps executing in-line. 它熄灭并完成它的事情,你的代码继续在线执行。 So if you check for the content immediately, it won't be there yet. 因此,如果您立即检查内容,它将不会存在。 It takes a while for the server to respond, send you the HTML and insert it into the DOM. 服务器需要一段时间才能响应,向您发送HTML并将其插入DOM。

You need to use a callback to do this. 您需要使用回调来执行此操作。 A callback is an event fired when an asynchronous event is complete. 回调是异步事件完成时触发的事件。

$('#result').load('../html/boo.html',function() { alert("moo, this is the callback") });

http://api.jquery.com/load/ http://api.jquery.com/load/

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

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