为什么这个jQuery代码隐藏了我的段落

why does this jquery code hide my paragraphs

本文关键字:我的 段落 隐藏 代码 jQuery 为什么      更新时间:2023-09-26

为什么这段代码输出 4 而所有其他内容都没有输出?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>jQuery</title>
    <script src="jquery-1.9.1.js"></script>
    <script>
    $(document).ready(function() {
      var par = $("p");
      document.write(par.length);
    });
    </script>
</head>
<body>
    <p>I am one</p>
    <p>I am two</p>
    <p>I am three</p>
    <p>I am four</p>
</body>
</html>

当文档准备好后调用 document.write 时,它会从文档中删除所有内容,因为它调用 document.open 会清除所有内容

看起来你想要的只是将par.length附加到身体上

$(document).ready(function() {
    var par = $("p");
    $('body').append(par.length);
});

当文档准备就绪时,您已经执行了脚本 - 很好。但是 document.write() 将直接写入现有的文档,替换那里的内容,因此您的段落消失了。

由于您使用的是jQuery,因此最好让jQuery为您添加项目:

$("body").append("<p>Paragraph count:"+$("p").length+"</p>");

在正文中创建另一个标签。

<div id="plength"></div>

然后添加如下所示的代码

$(document).ready(function() {
  var par = $("p");
  $('#plength').text(par.length);
});

运行示例 此处 http://jsfiddle.net/rajeshmepco/Bk6bZ/