小编And*_*rew的帖子

使用 jQuery 从单独文件中的模板加载 HTML 元素

我想通过使用 jQuery 从单独的文件加载 HTML 元素来构建网页。

我有的文件:

索引.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>
Run Code Online (Sandbox Code Playgroud)

应用程序.js

$.get("template.html",function(data) {
    let a = $(data).contents().clone()
    let b = a.find("#par1")
    a.html()
    $("body").append(b)   
 })
Run Code Online (Sandbox Code Playgroud)

模板.html

<template>       
    <div>
      <p id="par1">apple</p>
      <p id="par2">banana</p>
    </div>    
</template>
Run Code Online (Sandbox Code Playgroud)

当我加载index.html时,template.html中的 par1被加载到正文中,并呈现单词 apple 。这就是我想要的,但我不明白为什么我需要app.js中的“a.html()”行。如果我将其注释掉,则会收到错误:“Uncaught TypeError:无法读取 null 的属性‘包含’” $("body").append(b)。这里发生了什么?

html javascript jquery

5
推荐指数
1
解决办法
822
查看次数

标签 统计

html ×1

javascript ×1

jquery ×1