这是我的jQuery代码:
(function() {
var overlay = {
init: function() {
$('<div></div>', {
class: 'overlay'
})
.insertAfter('button');
}
};
overlay.init();
})();
我希望这会在我的按钮下放置一个div但是创建的HTML不包含div:
<body>
<button>Reveal More Info</button>
</body>
很抱歉,如果这是一个新手问题,我刚刚开始学习。
HTML主管:
<head>
<title>jQuery rules</title>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="script.js"></script>
<style>
body {
background: yellow;
}
button {
margin: 100px 0 0 200px;
}
div {
display: none;
width: 600px;
height: 400px;
background-color: white;
border-radius: 40px;
position: absolute;
left: 25%;
top: 30%;
}
</style>
</head>
答案 0 :(得分:2)
从jQuery文档中,请参阅例如http://api.jquery.com/jQuery/#jQuery-html-attributes:
块引用 名字&#34; class&#34;必须在对象中引用,因为它是一个JavaScript保留字,&#34; className&#34;不能使用,因为它引用了DOM属性,而不是属性。
答案 1 :(得分:0)
问题是你在标题中包含了script.js,它在按钮添加到dom之前执行,因此insertAfter()将无法找到插入div的button
。 / p>
此处的解决方案是使用document ready handler,或将脚本插入正文的底部(就在</body>
之前)
//dom ready handler
jQuery(function ($) {
var overlay = {
init: function () {
$('<div></div>', {
'class': 'overlay'
}).insertAfter('button');
}
};
overlay.init();
});
演示:Fiddle