How to create a click event on a random "div" inside the main "div"?

I have one main "Div" on which, after clicking, it is divided into an n X n matrix. On every click inside it with a random color div. This is still fine, now I want to create a click function on this random colorful div, which is currently located anywhere inside the entire main "div".

$(window).load(function() {
  var no = 1,
    $m = $(".main_div"),
    size = 200;

  $m.live('click', function() {
    no++;
    var n = no * no,
      i, _size;
    $m.empty();
    for (i = 0; i < n; i++)
      $m.append($('<div title=' + i + '/>'));
    _size = size / no;
    $m.find('> div').css({
      width: _size,
      height: _size
    });

    var colors = ["#FFFFFF", "#CC00CC", "#CC6699", "#0099CC", "#FF99FF"];
    var rand = Math.floor(Math.random() * colors.length),
      randomTotalbox = Math.floor(Math.random() * $('.main_div div').length);
    $m.find("div:eq(" + randomTotalbox + ")").css("background-color", colors[rand]);
    var rand = Math.floor(Math.random() * colors.length);
  });
});
  .main_div {
    width: 200px;
    height: 200px;
    background-color: #9F0;
  }
  .main_div > div {
    float: left;
    box-shadow: 0 0 1px #000;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main_div" id="demo">

</div>
Run codeHide result

Here is the fiddle ... Code

+4
source share
2 answers

so you say that the interactive div is added to the DOM whenever you click (e.g. on a button)

, divs ,

, .delegate

$('body').delegate('.main_div > div','click',function(){
  // here goes your instructions

});

: jQuery: .click() AND.on( "click" )

+1

, , NxN <div>, ,

 $(".main_div > div").on('click', function (evt) { ... } );

(2- ) click <div> , CSS, .

0

All Articles