【问题标题】:How to load the div of another webpage and not the entire page into my webpage?如何将另一个网页的 div 而不是整个页面加载到我的网页中?
【发布时间】:2014-11-27 06:45:57
【问题描述】:

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

我在 internal.html 中有以下代码,它将 external.html 加载到 id 为“result”的 div 中

   <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 加载到 internal.html 的 id 为“result”的 div 中,而不是整个页面?

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

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

加载页面片段

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

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

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

当这个方法执行时,它会获取ajax/test.html 的内容,然后jQuery 会解析返回的文档以找到ID 为container 的元素。此元素及其内容被插入到 ID 为 result 的元素中,而检索到的文档的其余部分将被丢弃。

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


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

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

【讨论】:

    【解决方案2】:

    用途:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多