简体   繁体   English

需要帮助调用函数

[英]Need help calling a function

I have a beginner and having trouble having the follow code run.我有一个初学者并且在运行以下代码时遇到问题。 When I hit the reset button the draw() function I defined does not seem to run/produce any output.当我按下重置按钮时,我定义的draw()函数似乎没有运行/产生任何输出。 The previous grid is erased but the new one is not created in its place.先前的网格会被擦除,但不会在其位置创建新的网格。

I cannot seem to figure out why.我似乎无法弄清楚为什么。 Any help would be greatly appreciated.任何帮助将不胜感激。

<!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');
        }
    }
};

The issue is because you remove the original .grid element which the hover event was bound to.问题是因为您删除了hover事件绑定到的原始.grid元素。 When you create the new .grid elements, the event is no longer bound.当您创建新的.grid元素时,事件不再受约束。 To solve this you need to use a delegated event handler:要解决此问题,您需要使用委托事件处理程序:

$('#container').on('mouseenter', '.grid', function(){
    $(this).css("background-color", "#00ffff");
});

Working example工作示例

You would have to hook to the mouseeenter event in this case as hover is not a standard event (it's a combined usage of mouseenter and mouseleave ).在这种情况下,您必须挂钩mouseeenter事件,因为hover不是标准事件(它是mouseentermouseleave的组合使用)。

Also note that, as stated by @hmd, you should call remove directly on the $('.grid') elements:另请注意,如@hmd 所述,您应该直接在$('.grid')元素上调用 remove :

$(".divbut").click(function() {
    $('.grid').remove();
    draw(16);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM