jQuery -- 生成元素的新属性未保存
jQuery -- new attribute of generated element 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
未生成。具有 class .generated
的元素是动态生成的 <a>
元素。
那是因为 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");
}
});
当我在动态生成的元素上创建新属性时,它没有保存:
$("#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
未生成。具有 class .generated
的元素是动态生成的 <a>
元素。
那是因为 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");
}
});