0

So, i want to know how if i append something to a div, where in this append i give a id to the element "a", i can get that id.

JS

$(document).ready(function () {
    console.log("ready!");
    $.ajax({
        type: "GET",
    contentType: "application/json; charset=utf-8",
    url: 'http://192.168.160.58/Formula1/api/Statistics/Champions',
    dataType: "json",
    success: function (data) {
                    for (var i = 0; i < data.length; i++) {
                        var k = data.length - i - 1;
                        if (i % 2 == 0) {
                            $(".timeline").append("<div class='container left'><div class='content'><center><h2><a id='" + data[k].Year + "' href='http://localhost:65418/StatisticsIntro.html'>" + data[k].Year + "</a></h2></center><center><img style='heigth:150px; width: 70px;' src ='" + data[k].ImageUrl + "' alt='" + data[k].DriverName + "'></img></center></div></div>");
                            
                        } else
                        if (i % 2 != 0) {
                            $(".timeline").append("<div class='container right'><div class='content'><center><h2><a id='" + data[k].Year +  "' href='http://localhost:65418/StatisticsIntro.html'>" + data[k].Year + "</a></h2></center><center><img style='heigth:200px; width: 70px;' src ='" + data[k].ImageUrl + "' alt='" + data[k].DriverName + "'></img></center></div>");
                        }
                    }
                }
    })
    $("a").click(function () {
        var myId = event.target.id;
        sessionStorage.setItem("myId", myId);
    })
 })

HTML

<div class="timeline"></div>

<script src="../Scripts/bootstrap.min.js"></script>
<script src="../Scripts/jquery-3.6.0.js"></script>
<script src="Timeline.js"></script>

When i imprime event.target.id i get null.

  • `$("a").click(function () {` -> `$(document).on("click", "a", function() {` – freedomn-m Jan 22 '22 at 15:45
  • Also your ` – freedomn-m Jan 22 '22 at 15:46
  • Why doesnt do the same thing? (or its better if i go read de doc?) – Hirohana Hiro Jan 22 '22 at 15:47
  • `$("a")` only applies to elements that exist at the time - your elements don't exist at that time as they are created later in the ajax callback - so you need event delegation (or put the handler in the callback, event delegation is clearer) – freedomn-m Jan 22 '22 at 15:50
  • So, has the same efect as this '$(document).ready(function () {' ? – Hirohana Hiro Jan 22 '22 at 15:52
  • No - doc.ready waits for the DOM to load. You have an ajax call, which starts after the DOM has loaded and finished after your original `$("a").click` line. The ajax call could be at any time (eg after clicking a button) while doc.ready is already at the page load. – freedomn-m Jan 22 '22 at 16:00

0 Answers0