首页 > 解决方案 > 从同一域中的不同 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>

标签: jquery

解决方案


你不能有多个<html>元素。您加载的代码不应包含<html>包装器,它应该只是<div>.

您可以通过将 ID 添加到.load()呼叫来解决此问题。

$("#content").load("tabla/test.html #fbody");

但这也可能行不通。jQuery 使用浏览器内置的 HTML 解析器,将返回的 HTML 放入<div>标签中,然后对其进行解析。如果 Firefox 丢弃所有 HTML 因为它在 inside <html>,这也会失败。最好的解决方案是修复只加载一个只包含 DIV 的脚本,而不是<html>.

这种形式的.load()不被弃用。唯一不推荐使用的方法是.load()用于事件处理程序。


推荐阅读