我创建了一个像素网格,希望它在悬停时变为黑色。 问题是该事件无法正常工作。
$(document).ready(function() {
function makeGrid(k) {
var size = 320 / k;
for (var i = 0; i < k; i++) {
$(".container").append("<div class=row></div>");
}
for (var j = 0; j < k; j++) {
$(".row").append("<div class=square></div>");
}
$('.square').css({
'height': size,
'width': size
});
}
$('.square').hover(function() {
$(this).addClass(".hover");
})
$('.reset').on('click', function() {
$(".container").empty();
makeGrid(16);
})
$('.start').on('click', function() {
var n = prompt("Set the size");
$(".container").empty();
makeGrid(n);
})
})
.square {
border-collapse: collapse;
display: inline-block;
}
.container {
text-align: -webkit-center;
position: relative;
top: 50px;
margin: 0 auto;
border: 1px solid #000000;
width: 320px;
height: 320px;
border-collapse: collapse;
}
.row {
clear: both;
content: "";
height: 20px;
}
.hover {
background-color: black;
}
button {
text-align: center;
background-color: white;
display: inline-block;
font-size: 20px;
border-radius: 2px;
top: 50%;
}
.wrap {
text-align: -webkit-center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="wrap">
<button class="clear">New Grid</button>
<button class="start">Start</button>
<button class="reset">Reset</button>
</div>
<div class="container"></div>
答案 0 :(得分:2)
由于您动态添加了div,因此无法使用.hover()
,而必须使用.on()
代替mouseenter
。使用.addClass()
时,您只需使用课程&#39;名称没有句点作为前缀。
$(document).ready(function() {
function makeGrid(k) {
var size = 320 / k;
for (var i = 0; i < k; i++) {
$(".container").append("<div class=row></div>");
}
for (var j = 0; j < k; j++) {
$(".row").append("<div class=square></div>");
}
$('.square').css({
'height': size,
'width': size
});
}
$(document).on("mouseenter", ".square", function(e) {
$(this).addClass("hover");
});
$('.reset').on('click', function() {
$(".container").empty();
makeGrid(16);
})
$('.start').on('click', function() {
var n = prompt("Set the size");
$(".container").empty();
makeGrid(n);
})
})
&#13;
.square {
border-collapse: collapse;
display: inline-block;
}
.container {
text-align: -webkit-center;
position: relative;
top: 50px;
margin: 0 auto;
border: 1px solid #000000;
width: 320px;
height: 320px;
border-collapse: collapse;
}
.row {
clear: both;
content: "";
height: 20px;
}
.hover {
background-color: black;
}
button {
text-align: center;
background-color: white;
display: inline-block;
font-size: 20px;
border-radius: 2px;
top: 50%;
}
.wrap {
text-align: -webkit-center;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="wrap">
<button class="clear">New Grid</button>
<button class="start">Start</button>
<button class="reset">Reset</button>
</div>
<div class="container"></div>
&#13;