如何正确使用.append()
How to properly use .append()
我最近开始学习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"
如果你坚持这样的间距,你的代码可能会变得非常混乱。
相关文章:
- React重新渲染但未显示正确的组件
- 我的jQuery插件参数没有正确启动,遇到了问题
- Jquery菜单操作不稳定,定位不正确,存在一般错误
- Amazon S3 REST API大小不正确
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- Javascript Reg Exp不正确匹配
- Javascript计数器变量未显示正确的值
- MeteorJS:在带有回调的vzaar api上正确使用wrapAsync
- Meteor方法在客户端返回null,在客户端运行的相同方法返回正确的值
- 将日期时间作为 JSON 发送将无法在我的视图中正确显示
- DIV并排,位置不正确
- 从查询字符串参数推断出正确的数据类型
- .append() 方法无法正确附加 php
- 无法让 append() 以正确的方式工作
- jquery append没有正确地附加样式图标
- 处理jQuery中.append()调用后计时的正确方法
- jQuery append:不能得到正确的引号
- jQuery append不正确显示浮点数
- 如何正确使用getElementById和innerHTML (.append())
- 如何正确使用.append()