我有一个初学者,无法运行以下代码。当我点击重置按钮时,我定义的draw()
功能似乎没有运行/产生任何输出。先前的网格已被删除,但新的网格未在其位置创建。
我似乎无法弄明白为什么。任何帮助将不胜感激。
<!DOCTYPE HTML>
<html>
<head>
<title>Etch-A-Sketch</title>
<link rel="stylesheet" type="text/css" href="CSS/styles.css"/>
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src = "JS/jquery.js"></script>
<meta charset="utf-8"/>
</head>
<body>
<h1>Etch-A-Sketch</h1>
<h3>Cameron Watson</h3>
<div id='container'></div>
<div class='divbut'>RESET</div>
</body>
</html>
#container {
border: 1px solid black;
height: 720px;
width: 720px;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
.grid {
height: 45px;
width: 45px;
float: left;
}
h1 {
text-align: center;
}
h3 {
text-align: center;
}
.divbut {
border: 1px solid black;
height: 45px;
width: 65px;
text-align: center;
}
$(document).ready(function() {
draw(16);
$('.grid').hover(function(){
$(this).css("background-color", "#00ffff");
});
$(".divbut").click(function(){
$('div').remove('.grid');
draw(16);
});
});
function draw(count){
for (x = 0; x < count; x++) {
for (y = 0; y < count; y++) {
$('<div>').addClass('grid').appendTo('#container');
}
}
};
答案 0 :(得分:1)
问题是因为您删除了.grid
事件所绑定的原始hover
元素。创建新的.grid
元素时,事件不再受约束。要解决此问题,您需要使用委托事件处理程序:
$('#container').on('mouseenter', '.grid', function(){
$(this).css("background-color", "#00ffff");
});
在这种情况下你必须要挂钩mouseeenter
事件,因为hover
不是标准事件(它是mouseenter
和mouseleave
的综合使用)。
另请注意,正如@hmd所述,您应该直接在$('.grid')
元素上调用remove:
$(".divbut").click(function() {
$('.grid').remove();
draw(16);
});