在 HTML 文档之外使用 Jquery 的 append()

Using append() from Jquery outside the HTML document

本文关键字:Jquery append HTML 文档      更新时间:2023-09-26

我正在尝试在单独的.JS文件中使用 Jquery,因为将所有 JavaScript 代码排除在 HTML 文档之外将提高加载 HTML 文档的性能。

在这个例子中,我使用"index.html"和"main.js"

以下是索引.html:

    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>append demo</title>
      <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
      <script src="testJS/main.js"></script>
    </head>
    <body>
    <p>I would like to say: </p>

<!-- CODE BELOW MUST BE REMOVED FROM THIS DOCUMENT -->
    <script>
    $( "p" ).append( "<strong>Hello</strong>" );
    </script>
    </body>
    </html>

我想从 html 中删除代码并将其插入到 main 中.js但是下面的示例对我不起作用:

主.js:

p.append( "<strong>Hello</strong>" );

我也尝试过这个没有成功:

 $( "p" ).append( "<strong>Hello</strong>" );

我该如何解决这个问题,将 JavaScript 放入内部和将其放在 .js 文件中有什么区别?

我建议使用 JQuery 提供的 $( document ).ready() 函数,如下所示:

$(document).ready(function() {
    $("p").append( "<strong>Hello</strong>" );
});

在这里您可以找到更多信息:http://learn.jquery.com/using-jquery-core/document-ready/

您需要在 dom ready 处理程序中添加代码,因为

其他明智的做法是,当代码被执行时,p 元素仍然没有添加到 dom 中 - 这是因为因为main.js是在标记中的 p 元素之前添加的,但无论如何最安全的选择是使用 dom ready 处理程序进行 dom 操作

jQuery(function($){
    $( "p" ).append( "<strong>Hello</strong>" );
})

使用外部 js 时,您必须将代码包装在文档就绪函数中,如下所示

$(function(){
  $('p').append('<strong>Hello</strong>');
});

*注意 - $(function(){$(document).ready(function(){的简写

正如 Arun P Johny 所解释的那样,问题在于 js 代码在它所依赖的 DOM 元素准备就绪之前就已经执行了。

另一种解决方案是更改外部文件,以便它定义一个函数,然后在 html 文件中正文的末尾调用该函数。

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>append demo</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="testJS/main.js"></script>
</head>
<body>
<p>I would like to say: </p>
<script>
  writeText();
</script>
</body>
</html>

<!-- main.js -->
function writeText(){
  $( "p" ).append( "<strong>Hello</strong>" );
}