【发布时间】:2020-02-24 10:01:02
【问题描述】:
我想通过使用 jQuery 从一个单独的文件中加载 HTML 元素来构建一个网页。
我拥有的文件:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script src="app.js"></script>
</body>
</html>
app.js
$.get("template.html",function(data) {
let a = $(data).contents().clone()
let b = a.find("#par1")
a.html()
$("body").append(b)
})
template.html
<template>
<div>
<p id="par1">apple</p>
<p id="par2">banana</p>
</div>
</template>
当我加载 index.html 时,来自 template.html 的 par1 被加载到正文中,并呈现了单词 apple。这就是我想要的,但我不明白为什么我需要 app.js 中的“a.html()”行。如果我将其注释掉,我会在$("body").append(b) 所在的行收到错误:“未捕获的 TypeError:无法读取属性 'contains' of null”。这是怎么回事?
【问题讨论】:
标签: javascript jquery html