Javascript 如何正确使用.append()
我最近开始学习jQuery,遇到了一些问题。 由于我来自C/C++的背景,jQuery的代码格式并不熟悉 所以,我的问题是.append()似乎并没有被追加。我最近一直在编写一个脚本,在jQuery中创建一个弹出窗口,需要在主体中添加一个元素。什么也没发生。经过进一步测试,append()似乎不起作用。我的结论是我可能误用了它,但我不知道怎么用Javascript 如何正确使用.append(),javascript,jquery,html,css,Javascript,Jquery,Html,Css,我最近开始学习jQuery,遇到了一些问题。 由于我来自C/C++的背景,jQuery的代码格式并不熟悉 所以,我的问题是.append()似乎并没有被追加。我最近一直在编写一个脚本,在jQuery中创建一个弹出窗口,需要在主体中添加一个元素。什么也没发生。经过进一步测试,append()似乎不起作用。我的结论是我可能误用了它,但我不知道怎么用 $('#contact').click(function (e) { $('#about').append('<h1>test<
$('#contact').click(function (e) {
$('#about').append('<h1>test</h1>');
e.preventDefault();
});
$(“#联系人”)。单击(功能(e){
$('#about')。追加('test');
e、 预防默认值();
});
编辑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)。
元素位于底部。您的代码看起来不错。确保在HTML中也有这些div。
这是我对您的代码所做的JSFIDLE,它工作得非常好
我用来测试的HTML
<span id="contact">Click me</span>
<div id="about">
</div>
这样写:
id="Contact" class="nav"
如果您坚持这样的间距,代码可能会变得非常混乱。
$(“#联系人”)。单击(功能(e){
$('#about')。追加('test');
e、 预防默认值();
});代码>
这是div“关于”。
单击此处查看一些操作
您的html中的ID是大写的(联系人
,而不是联系人
),但您在JavaScript中使用的是所有小写字母。还要更改jQuery选择器:
$('#Contact').click(function (e) {
$('#About').append('<h1>test</h1>');
e.preventDefault();
});
$(“#联系人”)。单击(功能(e){
$('#About')。追加('test');
e、 预防默认值();
});
或者在HTML中将ID设置为小写:
<a href="#about" id="about" class="nav">About</a>
<a href="#contact" id="contact" class="nav">Contact</a>
这似乎是一个至关重要的问题,很好地解决了啊,非常感谢!我看了电影,因为我是个白痴。一定是忘了我的咖啡!谢谢@eisbehrSorry,但你犯了一个错误,现在投了反对票。问题是你的,我让你看到代码是有效的。stack overflow不是学习资源@Laurianti吗?不需要否定性。@JamesBalajan如果这个答案解决了你的问题,我建议你向社区展示。因为。虽然这个代码片段可以解决这个问题,但确实有助于提高你文章的质量。请记住,您将在将来回答读者的问题,这些人可能不知道您的代码建议的原因。还请尽量不要用解释性注释挤满您的代码,因为这会降低代码和解释的可读性!
<a href="#about" id="about" class="nav">About</a>
<a href="#contact" id="contact" class="nav">Contact</a>