简体   繁体   中英

How to attach onclick event to an element dinamically created

I'm trying to trigger an event attached to a html tag

This table is builded insde a function

    function detail(id){
      console.log(id)
    }

function search(data){
                $.post(url, {valorBusqueda: textoBusqueda}, function(data) {

                    data = JSON.parse(data);

                        $.each(data, function(i, val){

                                id = val.id;


                                html += '<tr onclick="detail('+id+')">';
                                html += '<tr>';
                            }
                        });      

                 }); 
}

But when I click the element I get this err:

Uncaught ReferenceError: detallePaciente is not defined

when is actually defined in my file

any idea how could I solve this?

Change this line:

html += '<tr class="clickedclass" data-id = "' + id + '">';

And make alert from this in Jquery:

$("body").on("click", ".clickedclass", function(){
  var id = $(this).attr("data-id");
  console.log(id);
});

You have a syntax error in your function declaration.

It should be:

function detail(data) {
...
}

Same error with the search function. Would need to see how you attach it to the click event to help with that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM