如何正确使用.append()

Jam*_*jan -4 html javascript css jquery

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

所以,我的问题是.append()似乎没有附加.我最近一直在编写一个脚本来在jQuery中创建一个弹出窗口,并且需要向body添加一个元素.没啥事儿.进一步测试后,.append()似乎没有用.我的结论是我可能会滥用它,但我不知道如何.

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

编辑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>
Run Code Online (Sandbox Code Playgroud)

只包含了一些html以节省空间(我附加区域中的html).所述<script>元件是在底部.

eis*_*ehr 6

你的html中的id是大写的(Contact而不是contact),但你在JavaScript中使用全部小写.也改变jQuery选择器:

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

或者在HTML中使用小写的id:

<a href="#about" id="about" class="nav">About</a>
<a href="#contact" id="contact" class="nav">Contact</a>
Run Code Online (Sandbox Code Playgroud)

  • @JamesBalajan如果这个答案解决了你的问题,我建议你[接受](http://stackoverflow.com/help/accepted-answer)向社区展示. (2认同)