如何正确使用.append()

How to properly use .append()

本文关键字:append 何正确      更新时间:2023-09-26

我最近开始学习jQuery,并且遇到了一些问题。jQuery的代码格式是不熟悉的,因为我来自C/c++的背景。

所以,我的问题是。append()似乎根本没有追加。我最近一直在做一个脚本,使jQuery弹出,并需要追加一个元素的身体。什么也没有发生。经过进一步测试,.append()似乎不起作用。我的结论是,我可能滥用了它,但我不知道如何。

$('#contact').click(function (e) {
    $('#about').append('<h1>test</h1>');
    e.preventDefault();
});

编辑1:请求Html

<!DOCTYPE html>
<html>
  <head>
    <title>Canteen Mate</title>
    <link rel="stylesheet" type="text/css"
          href="https://fonts.googleapis.com/css?family=Roboto">
    <link rel="stylesheet" type="text/css"
          href="https://fonts.googleapis.com/css?family=Roboto+Condensed">
    <link rel="stylesheet" type="text/css"
          href="https://fonts.googleapis.com/css?family=Ubuntu">
    <link rel="stylesheet" type="text/css" href="css/home.css">
  </head>
  <body>
    <div class = "nav_wrapper" id = "nav_wrapper">
      <nav>
        <ul>
          <li class = "current"><a href="#nav_wrapper" id = "Home" class =      "nav">Home</a></li>
          <li><a href="#about" id = "About" class = "nav">About</a></li>
          <li><a href="#contact" id = "Contact" class = "nav">Contact</a>    </li>
    </ul>
  </nav>
</div>
<div class = "wrapper">
  <img src="images/newfood.jpg" alt="Food" class="luncho">
  <div class = "text">
    <h1 class = "motto">Ordering from the canteen has never been so simple<br>
    <p class = "motto-description" id = "about">Order food from your canteen from
    anywhere as long as you have data.</p></h1>
  </div>
</div>

为了节省空间,只包含了一些html(我要添加的区域中的html)。<script>元素在底部

你的id在你的html是大写的(Contact,而不是contact),但你在你的JavaScript中使用所有小写字母。也更改jQuery选择器:

$('#Contact').click(function (e) {
    $('#About').append('<h1>test</h1>');
    e.preventDefault();
});

或者在HTML中使用小写id:

<a href="#about" id="about" class="nav">About</a>
<a href="#contact" id="contact" class="nav">Contact</a>

$('#contact').click(function (e) {
    $('#about').append('<h1>test</h1>');
    e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="about">this is div "about".</div>
<div id="contact">click here to see some action</div>

您的代码看起来不错。确保在HTML中也有这些div。这是我用你的代码做的JSFiddle,它工作得很好。

https://jsfiddle.net/edtqpvym/

用于测试 的HTML
<span id="contact">Click me</span>
<div id="about">
</div>

编辑:你必须注意大小写字母!在HTML中,你用大写字母命名div ID,在JQuery中,你用小写字母命名它们。这就解决了你的问题。用小写字母命名div是个好习惯。另外,在=

前面不能加空格
id = "Contact" class = "nav"

这样写:

id="Contact" class="nav"

如果你坚持这样的间距,你的代码可能会变得非常混乱。