jQuery, how to address the dynamic subsidiary



  • I don't know how to turn to only one of the subsidiaries of the class created dynamically.

    $('#next').click(function()
    {
     var rnd = Math.floor(Math.random()*1000);
     var html = '<div>'+rnd+'</div>';
     $(html).attr('id', rnd).addClass('order').prependTo('#orders');
     console.log(rnd);
    

    $('.order').click(function() //тут проблема
    {
    console.log($(this).attr('id'));
    });

    });

    .order {
    display: block;
    padding: 5px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id='next'>More</button>
    <div id='orders'>
    <div class='order'>Y</div>
    <div class='order'>X</div>
    </div>



  • You're calling method .click() inside the existing method .click(), there's a recurring challenge to the function. To avoid this, a second target click beyond the first function will be required:

    $('#next').click(function()
    {
     var rnd = Math.floor(Math.random()*1000);
     var html = '<div>'+rnd+'</div>';
     $(html).attr('id', rnd).addClass('order').prependTo('#orders');
     console.log(rnd);
    

    });

    $('body').on('click', '.order', function() //тут нет проблемы
    {
    console.log($(this).attr('id'));
    });

    .order {
    display: block;
    padding: 5px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id='next'>More</button>
    <div id='orders'>
    <div class='order'>Y</div>
    <div class='order'>X</div>
    </div>




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2