JQuery代码在控制台中工作,但不在脚本标记或外部js文件中

时间:2016-01-13 02:49:31

标签: javascript jquery

我正在尝试使用从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>

非常感谢任何帮助!

2 个答案:

答案 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">&nbsp;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;
}