Getting element id with jquery

前端 未结 4 800
庸人自扰
庸人自扰 2021-01-27 15:24

The code should print the id of the selected div but it does not. I did not find the error. Thanks for help.

HTML


   
相关标签:
4条回答
  • 2021-01-27 15:47

    To access id use 'on' as your div is dynamically generated:

    $(document).ready(function() {
       $('#form_area').on('click', '.form_row', function () {
            console.log(this.id);
        });
    });
    
    0 讨论(0)
  • 2021-01-27 15:48

    Firstly, you have jQuery - you should use that to register your event handlers instead of using obsolete, error prone inline event handlers.

    Secondly, your button handler is inside #formarea and so is also triggering the click handler since the button's parent has no ID. This is probably not desired.

    Thirdly, your event handlers need to be delegated because you're trying to catch events on dynamically added elements.

    So, remove the onclick attribute and add this:

    $('#formarea button').on('click', addRow);
    
    $('#formarea').on('click', '.form_row', function() {  // delegated, for dynamic rows
        console.log(this.id);                            // NB: not $(this).attr('id') !!
    });
    
    function addRow(ev) {
        // unmodified
    }
    

    See http://jsfiddle.net/alnitak/aZTbA/

    0 讨论(0)
  • 2021-01-27 15:50

    Ok, I think I understand what you are missing. You are trying to log the ID after adding a row using add_row function,

    .form_row is added dynamically to the DOM. So when executing $('.form_row').click(, there is no .form_row to bind the handler. The below way of using .on method binds the handler to #form_area and executes the handler only when the click event is from .form_row

    $('#form_area').on('click', '.form_row', function () {
       console.log(this.id);
    });
    

    $('#form_area div') selects the div inside the div #form_area which doesn't have an ID

    Below comment in html shows which div is selected,

    <div id="form_area">
       <div>  <!-- $('#form_area div') selects this div-->
          <button onclick="return add_row();" style="width:100%;">Add Row</button>
       </div>
    </div>
    
    0 讨论(0)
  • 2021-01-27 16:05

    Try console.log($('#form_area div').attr('id'));

    0 讨论(0)
提交回复
热议问题