jquery - 从同一域中的不同 html 文件加载 div
问题描述
我想从同一个域中的不同 html 文件加载一个 div。我怎么能用jquery做到这一点?
下面是我的示例,但它不起作用。过去我使用过 .load() 但现在已弃用。我当前的浏览器是 Firefox 72.0.2。64 位。
请记住,在旧的 Firefox 浏览器中它可以工作(如 Firefox 60.0),但在新的 Firefox 浏览器中它不起作用。
请您用完整的解决方案编写代码。我是 Jquery 的新手。
谢谢。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
$(document).ready(function(){
$("#boton").click(function(){
$.get("tabla/test.html", function(data){
$("#content").html(data);
});
});
});//End jquery.
</script>
</head>
<body>
<h2>Let's see how load the text file from another html file.</h2>
<input type="button" id="boton" value="Load an external HTML file">
<div id="content">
<p>Here will be loaded the text.</p>
</div>
</body>
</html>
<html>
<!-- This is the other web page named: test.html -->
<div id="fbody">
<p>Hi, this is the text from antoner html file.</p>
</div>
</html>
解决方案
你不能有多个<html>
元素。您加载的代码不应包含<html>
包装器,它应该只是<div>
.
您可以通过将 ID 添加到.load()
呼叫来解决此问题。
$("#content").load("tabla/test.html #fbody");
但这也可能行不通。jQuery 使用浏览器内置的 HTML 解析器,将返回的 HTML 放入<div>
标签中,然后对其进行解析。如果 Firefox 丢弃所有 HTML 因为它在 inside <html>
,这也会失败。最好的解决方案是修复只加载一个只包含 DIV 的脚本,而不是<html>
.
这种形式的.load()
不被弃用。唯一不推荐使用的方法是.load()
用于事件处理程序。
推荐阅读
- node.js - 公开响应头 Nodejs
- math - 在机器人框架中四舍五入的问题
- mysql - 使用 JSON API 响应时 Sequelize 事务失败
- parse-platform - 如何在 back4app 解析服务器中使用两个 useParseQuery 挂钩来实现一对一聊天应用
- mongodb - MongoDB 聚合分组条件
- python - 悖论python算法
- php - URL 不使用 .htaccess 从公用文件夹重定向到 static4 文件夹?
- r - 使用循环在 ggplot2 中绘制多个箱线图,长数据帧
- c++ - 我的实现树的高度有什么问题?
- java - 是否可以创建一个可以与 Java 中的集合一起使用的泛型类?