jquery load 函数在我的代码上不起作用.这是为什么

The jquery load function is not working on my code. Why is this?

本文关键字:不起作用 为什么 代码 load 函数 我的 jquery      更新时间:2023-09-26

我刚刚开始使用jquery并有以下代码:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("hello.txt #p1");
  });
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>

当我运行它时,它只是通过使我的div 变为空白来响应。当它应该只是放文本时。文本文件与 html 文档位于同一文件中。我将其设置为代码.php格式,并且文本文件.txt。

这是基于所提供的有限信息的有根据的猜测。

该行

$("#div1").load("hello.txt #p1");

将其分开:

  • load正在拨打Ajax电话以获取"hello.txt"。
  • 加载文档时,jQuery 解析文档并查找 id 为 "p1" 的元素。(这就是 #p1"是什么)
  • 该内容将加载到 id 为div1 的元素中

我的猜测是,您的文本文件中没有 id 为"p1"的元素。

所以要么给一个元素一个 id p1

<p id="p1">This is the new text to show.</p>

或者删除 p1 以便将其.load("hello.txt");

$("#div1").load("hello.txt #p1");

您正在尝试加载hello.txt的内容,使用 id="p1" 提取元素的内容,然后显示该内容。

文件内容如下:

This is a text file.

它不是 HTML 文档。它没有任何元素(ID p1或其他),因此找不到您要搜索的内容。

如果要加载整个内容,请从load字符串中删除#p1