【问题标题】:jQuery -- new attribute of generated element not savedjQuery——生成元素的新属性未保存
【发布时间】:2015-04-02 16:22:13
【问题描述】:

当我在动态生成的元素上创建新属性时,它没有被保存:

$("#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 未生成。类.generated 的元素是动态生成的&lt;a&gt; 元素。

【问题讨论】:

    标签: javascript jquery html web attr


    【解决方案1】:

    那是因为 this 在 AJAX 回调中是不同的

    $("#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");
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      • 2016-04-17
      • 1970-01-01
      相关资源
      最近更新 更多