jirinovo
jirinovo

Reputation: 2275

jQuery -- new attribute of generated element not saved

When I create new attribute on element, which was dynamically generated, it's not saved:

$("#div-main").on("mouseover", ".generated", function(e)
{
    console.log("hover");
    console.log($(this).attr("title")) // always undefined

    if (typeof $(this).attr("title") === typeof undefined)
    {
      $.get("<URL with PHP>", function(data)
        {
          if (data != "")
          {
            $(this).attr("title", data);
            console.log($(this).attr("title")); // data shows
          }
          else
          {
            $(this).attr("title", "no data");
            console.log($(this).attr("title")); // "no data" shows
          }
        });
    }
    else
    {
      console.log("'title' attribute already set");
    }
});

#div-main is not generated. Element with class .generated is dynamically generated <a> element.

Upvotes: 0

Views: 61

Answers (1)

tymeJV
tymeJV

Reputation: 104775

That's because this is different inside the AJAX callback

$("#div-main").on("mouseover", ".generated", function(e)
{
  console.log("hover");
  console.log($(this).attr("title")) // always undefined

  if (typeof $(this).attr("title") === typeof undefined)
  {
    var that = this; //CONTEXT
    $.get("<URL with PHP>", function(data)
    {
      if (data != "")
      {
        $(that).attr("title", data);
        console.log($(that).attr("title")); // data shows
      }
      else {
          $(that).attr("title", "no data");
          console.log($(that).attr("title")); // "no data" shows
      }
        });
    } else {
        console.log("'title' attribute already set");
    }
});

Upvotes: 2

Related Questions