【问题标题】:javascript not working to append to the end of the docmap div tag?javascript无法附加到docmap div标签的末尾?
【发布时间】:2020-02-04 13:47:37
【问题描述】:

我想知道为什么我的 javascript 无法附加到 docmap div 标签的末尾? 至少我在 chrome 中尝试过,我没有看到它说:“一些新内容!”在 docmap div 标签中。

<html>
<header>
<style>
#docmap {
  background-color: #f0f0f0;
  height: 100%;
  width: 200px;
  position: fixed; 
}
#main {
  margin-left: 200px;
  position: 200px; 
  padding: 20px;
}
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<script>
    //alert("hey!");
    var docmap = $("#docmap");
    docmap.append('<br>Some new content!');
</script>
</header>

<body>

<div id="docmap">
<ul>
<li> hello
<li> hi
<li> howdy
</ul>
</div>

<div id="main">
<h1>header1</h1>
<h2>header2 a</h2>
<h2>header2 b</h2>
<h1>header1 a</h1>
</div>

</body>
</html>

【问题讨论】:

  • 您的代码在标题中,DOM 甚至还不存在。要么使用准备好的 JQuery DOM,要么将你的脚本放在正文关闭标记之前。
  • 这样的话控制台不应该报错吗?
  • 不,jquery 对集合起作用,如果集合为空,它就什么也不做。
  • @pico 在这种情况下没有错误 - 您尝试使用 $("#docmap") 查找元素,但由于它不存在,因此您得到一个空集合。当你试图用它做任何事情时,它只是一个空操作。
  • @pico 是的,使用$(document).ready()

标签: javascript html


【解决方案1】:

&lt;html&gt; 标签中,您应该使用&lt;head&gt;&lt;header&gt; 是另一个用途的标签。此外,在声明要使用 JQuery 调用的标记之后,您必须将脚本移动到正文的底部。

Try it Online! 或直接在这里:

    //alert("hey!");
var docmap = $("#docmap");
docmap.append('<br>Some new content!');
#docmap {
  background-color: #f0f0f0;
  height: 100%;
  width: 200px;
  position: fixed; 
}
#main {
  margin-left: 200px;
  position: 200px; 
  padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="docmap">
<ul>
<li> hello
<li> hi
<li> howdy
</ul>
</div>

有一个关于&lt;head&gt; vs &lt;header&gt;的问答:<header> vs. <head>

如果您想知道在哪里放置 &lt;script&gt; 标签,那么您一定会支持:

【讨论】:

    猜你喜欢
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多