jQuery - remove()不起作用

Moh*_*qui 9 html javascript css jquery html5

我有一个脚本根据鼠标在页面主体上的位置放置div.我有一个显示"清除"的按钮,我想用它来清除创建的div.我怎样才能做到这一点?

我写的脚本和源代码:

HTML

<!DOCTYPE html>
<html>
    <body>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
        <script src="bhaiya.js"></script>
        <button style="z-index: 2000;" class="clear" onclick="clear()">Clear</button>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

jQuery的

$(document).ready(function(){

    $(this).mousedown(function(e){
        $x = e.pageX;
        $y = e.pageY;

        $div = "<div class='theDiv' style='width: 250px; height: 150px; background-color:#e7e7e7; position: absolute; top:" + $y + "px; left:" + $x + "px;'>Hey</div>";
        $("body").prepend($div);
    });

    function clear() {
        $(".theDiv").remove();
    }

})
Run Code Online (Sandbox Code Playgroud)

jsFiddle: http ://jsfiddle.net/BpAYz/

任何帮助,将不胜感激 :)

nnn*_*nnn 10

内联html属性事件处理程序只能调用全局函数.您的clear()函数不是全局函数,因为它是文档就绪处理程序中定义的,因此您onclick="clear()"无法找到它.你需要将函数移到ready处理程序之外(使其成为全局函数),或者更好的是,使用jQuery绑定click:

$(document).ready(function(){    
    $(this).mousedown(function(e){
        var $x = e.pageX;
        var $y = e.pageY;    
        var $div = "<div class='theDiv' style='width: 250px; height: 150px; background-color:#e7e7e7; position: absolute; top:" + $y + "px; left:" + $x + "px;'>Hey</div>";
        $("body").prepend($div);
    });

    $(".clear").click(function () {
        $(".theDiv").remove();
    });
});
Run Code Online (Sandbox Code Playgroud)

另请注意,我已经var在mousedown处理程序中添加了变量:没有var它们成为全局变量,这只会使您的代码更容易出错且难以调试.(除非你有充分的理由说它们应该是全局的吗?)