我正在尝试使用从div元素创建的框网格创建Etch-A-Sketch,但处理框突出显示的代码(mouseenter方法)不起作用。但是,当代码放在控制台中时它会起作用,因此我对导致问题的原因感到困惑。
<script>
$('button').click(function() {
$('#container').empty();
var row = prompt("How many rows are desired?");
var col = prompt("How many columns are desired?");
for (var j=0; j<=row; j++) {
for (var i=0; i<=col; i++) {
$('#container').append('<div class="grid-box"></div>');
};
$('#container').append('<div class="next-row"></div>');
};
$('.grid-box').mouseenter(function() {
$(this).css('background-color', "red");
});
});
</script>
非常感谢任何帮助!
答案 0 :(得分:1)
.grid-box
中不存在 DOM
元素?尝试使用事件委派。见Understanding Event Delegation
// delegate `mouseenter` event to `.grid-box` parent element `#container`
$("#container").on("mouseenter", ".grid-box", function() {
$(this).css('background-color', "red");
});
$('button').click(function() {
$('#container').empty();
var row = prompt("How many rows are desired?");
var col = prompt("How many columns are desired?");
for (var j=0; j<=row; j++) {
for (var i=0; i<=col; i++) {
$('#container').append('<div class="grid-box"></div>');
};
$('#container').append('<div class="next-row"></div>');
};
});
答案 1 :(得分:0)
您的循环计数错误,请查看我的fiddle
<强> HTML 强>
<button>Start</button>
<div id="container"></div>
<强> JS 强>
$('button').click(function() {
$('#container').empty();
var row = prompt("How many rows are desired?");
var col = prompt("How many columns are desired?");
for (var j=0; j<col; j++) {
for (var i=0; i<row; i++) {
$('#container').append('<div class="grid-box"> o</div>');
};
$('#container').append('<div class="next-row"></div>');
};
$('.grid-box').mouseenter(function() {
$(this).css('background-color', "red");
});
});
<强> CSS 强>
.grid-box {
float: left;
width: 25px;
height: 25px;
}
.next-row{
clear: both;
}