Getting element id with jquery

前端 未结 4 803
庸人自扰
庸人自扰 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: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/

提交回复
热议问题