如何将另一个网页的div而不是整个网页的div加载到我的网页中? [英] How to load the div of another webpage and not the entire page into my webpage?

查看:135
本文介绍了如何将另一个网页的div而不是整个网页的div加载到我的网页中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个网页internal.html和external.html

I have two webpages internal.html and external.html

我在internal.html中有以下代码,该代码将external.html加载到ID为结果"的div中

I have the following piece of code in internal.html which loads external.html into div with id "result"

   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
   <script>
function autoRefresh_div()
{
      $("#result").load("https://abc/external.html");// a function which will load data from other file after x seconds
 }

  setInterval('autoRefresh_div()', 5000); // refresh div after 5 secs
            </script>

我在external.html中有一个ID为"test"的div.
如何仅将external.html的ID为"test"的div加载到id为"result"的internal.html的div中而不是整个页面中?

I have a div with id "test" in external.html.
How do I load only the div with id "test" of external.html into internal.html's div with id "result" and not the entire page?

推荐答案

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

正在加载页面片段

.load()方法与$ .get()不同,它允许我们指定要插入的远程文档的一部分.这可以通过使用url参数的特殊语法来实现.如果字符串中包含一个或多个空格字符,则假定字符串中第一个空格之后的部分是确定要加载内容的jQuery选择器.

The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

我们可以修改上面的示例以仅使用获取的文档的一部分:

We could modify the example above to use only part of the document that is fetched:

$( "#result" ).load( "ajax/test.html #container" );

执行此方法时,它会检索ajax/test.html的内容,但是jQuery会解析返回的文档以查找具有容器ID的元素.该元素及其内容将插入具有ID ID为result的元素中,而其余的检索文档将被丢弃.

When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.

jQuery使用浏览器的.innerHTML属性来解析检索到的文档并将其插入到当前文档中.在此过程中,浏览器经常从文档中过滤元素,例如,或.结果,由.load()检索的元素可能与由浏览器直接检索的文档不完全相同.

jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as , , or elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.

在您的情况下,您需要将代码修改为:

In your case you'll want to modify your code to:

$("#result").load("https://abc/external.html #test")

这篇关于如何将另一个网页的div而不是整个网页的div加载到我的网页中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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