-1

I'm trying to add a handler to a tr that is generated in JQuery but it doesn't respond. Each row is meant to open a different view.

someArray.forEach(
    function (element) {           
       $('#table').append("<tr id='" + element.id +"'</tr>").ready(
          function() {
            $("#" + class.id).on("click", function () {
                $("body").load("OtherView.html");                   
            })
    });     
 });
Jon P
  • 19,442
  • 8
  • 49
  • 72

1 Answers1

2

Here's how I'd do it. Use on for dynamically binding and use a data attribute to hold the new target. Something like:

var someArray = [{id:1, target:"View.html"},{id:2, target:"OtherView.html"},{id:3, target:"SomeOtherView.html"}]

//Dynamically bind the click event
$("#table").on("click", "tr", function(){
  //Add your logic here
  console.log($(this).data("target"));
});

//Populate the table
someArray.forEach(function (element) {           
       $('#table').append(`<tr id='${element.id}' data-target='${element.target}'><td>${element.target}</td></tr>`);     
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table"></table>

Some suggested reading:

Ideally I would have done the table updated with a document fragment to reduce the number of DOM updates, but I didn't want to change things too much.

Jon P
  • 19,442
  • 8
  • 49
  • 72