如何计算使用Javascript删除的气泡?

时间:2014-03-12 19:23:42

标签: javascript

我有一堆泡泡,我可以点击并使用我编写的javascript代码删除它们。我现在正试图弄清楚每次删除气泡时如何计算它。这是html和javascript:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Bubbles</title>
<link href="bubbles.css" rel="stylesheet">
<script src="scripts/jquery-1.10.2.min.js"></script>
<script src="scripts/bubbles.js"></script>
<script src="scripts/java.js"></script>
</head>

<body>
<!--background bubbles-->
<div id="b-blue" class="b" data-speed="1"></div>
<div id="b-green" class="b" data-speed="2"></div>
<div id="b-red" class="b" data-speed="4"></div>

<!--bubble text-->
<div id="bText">
    B<br />U<br />B<br />B<br />L<br />E<br />S<br />!
</div>

<!--bubble game-->
<div id="bubbleGame">
    <!-- <div class="bubble"></div> -->
</div>

<!--bubble score and reset-->
<div id="bottomCorner">
    <div id="reload">refresh...</div>
    <div id="score">0</div>
</div>
</body>
</html>

用于删除气泡的Javascript

$(document).ready(function() {
$("#bubbleGame").on("click", ".bubble", function deleteb() {
$(this).remove();
})
})

每次我删除一个气泡我想在“得分”div中添加一个。所有气泡都在“buublegame”div中,类别为“.bubble”我知道我已经使用了jquery但是没有一种方法会更好。此外,点击刷新按钮,以20个气泡重新进入页面。

2 个答案:

答案 0 :(得分:1)

$("#bubbleGame").on("click", ".bubble", function deleteb() {
    $(this).remove();
    $('#score').text( parseInt( $('#score').text() ) + 1 ); 
})

jsfiddle

答案 1 :(得分:1)

关闭练习怎么样:

function make_counter () {
    var i=0;
    return function () {
        i++;
        $('#score').text(i);
    }
}

$(document).ready(function() {
    counter = make_counter();
    $("#bubbleGame").on("click", ".bubble", function deleteb() {
        $(this).remove();
        counter();
    })
})

JSFiddle here上展示。

修改

我采用了稍微不同的重置功能方法:

$(document).ready(function() {
    var counter = {
        i: 0,
        incr: function () {
            this.i++;
            this.update();
        },
        reset: function () {
            this.i = 0;
            this.update();
        },
        update: function () {
            $('#score').text(this.i);
        }
    }

    $("#bubbleGame").on("click", ".bubble", function deleteb() {
        $(this).remove();
        counter.incr();
    });

    $("#reload").click(function () {        
        var i;
        $("#bubbleGame .bubble").remove();        
        for (i = 0; i < 20; ++i) {
            $("#bubbleGame").append($("<div class='bubble'>"));
        }
        counter.reset();
    });
});

JSFiddle for this one