单击后使div消失

时间:2015-02-03 19:21:00

标签: javascript jquery html css

我让圆圈div随机掉落。当我点击一个圆圈时,我希望它消失,我希望分数增加一个。

这是我的代码:

function CreateDiv() {
    var ranLeft1 = Math.floor((Math.random() * 700) + 1);
    var ranInterval = 1000 + Math.floor((Math.random() * 5000) + 1);
    jQuery('<div class="droper1" id="droper1" onclick="myFunction()" />').css({top: 20, left: ranLeft1 }).animate({top: "+=573px"}, 9000 ).appendTo('#container' );
    window.setTimeout( CreateDiv, ranInterval );
}

var score = 0;
document.getElementById("myBtn").addEventListener("click", myFunction);
function myFunction() {
    score++;
    //make the div dissapear after one click on it .. how ??!!
    document.getElementById("score").innerHTML = score;
}

4 个答案:

答案 0 :(得分:1)

你可以尝试这个(注意:这是来自内存和未经测试的)

function CreateDiv() {
    var ranLeft1 = Math.floor((Math.random() * 700) + 1);
    var ranInterval = 1000 + Math.floor((Math.random() * 5000) + 1);
    jQuery('<div class="droper1" onclick="myFunction()" />').css({top: 20, left: ranLeft1 }).animate({top: "+=573px"}, 9000 ).appendTo('#container' );
    window.setTimeout( CreateDiv, ranInterval );
}

var score = 0;

$(document).on("click", ".droper1", function() {
    score++;
    $("#score").innerHtml(score);
    $(this).remove();
});

答案 1 :(得分:1)

您希望点击remove() $(this),但使用委派比将点击方法直接分配给每个新生成的div更快:

var div_counter=0;
function CreateDiv() {
    var ranLeft1 = Math.floor((Math.random() * 700) + 1);
    var ranInterval = 1000 + Math.floor((Math.random() * 5000) + 1);
    jQuery('<div class="droper1" id="'+ ++div_counter +'" />').css({top: 20, left: ranLeft1 }).animate({top: "+=573px"}, 9000 ).appendTo('#container' );
    window.setTimeout( CreateDiv, ranInterval );
}

var score = 0;

$('body').on('click', '.droper1', function(){
   score++;
   $(this).remove();
});

答案 2 :(得分:0)

这应该做你想要的Memo Awaw。

  

当我点击一个圆圈时,我希望它消失,我想得分   增加一个。

以下加载代码会创建一个单击功能。单击其中一个圆圈后,div将被删除(但如果需要,也可以使用隐藏)。分数增加1。出于测试原因,我离开了console.log(),因此您可以选择在检查器中看到您的分数增加。

&#13;
&#13;
jQuery(document).ready(function() {

  var score = 0;
  $('.foo').on('click', function() {
    jQuery(this).remove();
    score++;
    console.log("New score is: " + score);
  });

});
&#13;
.foo {
  border-radius: 50%;
  width: 20px;
  height: 20px;
  background-color: blue;
  text-indent: -10000px;
}
.foo:hover {
  cursor: crosshair;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='foo' id=1>content</div>
<div class='foo' id=2>content</div>
<div class='foo' id=3>content</div>
<div class='foo' id=4>content</div>
&#13;
&#13;
&#13;

答案 3 :(得分:-2)

$('#myBtn').on('click', function(){
     $('droper1').hide();
});
相关问题