If you use aid
in an onxyx
-attribute-style event handler, it has to be a global. That's one of many reasons not to use them.
Instead, hook up the event handler with modern handling, store the aid
on the link as a data-*
attribute, and retrieve it in reject
:
// *** Removed `onClick` and `id="aid"` from this string
var message_container = '<div class=\"new-update clearfix\"><div class=\"update-done\"></br> </div> <a class=\"tip\" ><i style=\"font-size: 2em; float:right\" class=\"icon-remove\">remove link</i></a> </br></br> </div>';
$.ajax({
url : '/test/back-api/admin/announcements',
method : 'GET',
success : function(d) {
if (d.result) {
var posts = d.data;
for (var i = 0; i < posts.length; i++) {
var post = posts[i];
var aid = post.id;
//message.find('#aid').append("href", post.id);
// *** Hook it up and prepend it
$(message_container)
.find("a.tip")
.attr("data-aid", aid)
.on("click", reject)
.end()
.prependTo("#announcement-container");
// *** End of added bit
}
} else {
$('#announcement-container').append("<div> Nothing to show. </div>");
}
}
});
function reject() {
var aid = this.getAttribute("data-aid"); // *** Get the aid from the element
alert("reject aid = " + aid);
}
Note that I removed the id="aid"
from the string. You can't have the same ID on more than one element.
Live example:
// *** Removed `onClick` and `id="aid"` from this string
var message_container = '<div class=\"new-update clearfix\"><div class=\"update-done\"></br> </div> <a class=\"tip\" ><i style=\"font-size: 2em; float:right\" class=\"icon-remove\">remove link</i></a> </br></br> </div>';
fakeAjax({
url : '/test/back-api/admin/announcements',
method : 'GET',
success : function(d) {
if (d.result) {
var posts = d.data;
for (var i = 0; i < posts.length; i++) {
var post = posts[i];
var aid = post.id;
//message.find('#aid').append("href", post.id);
// *** Hook it up and prepend it
$(message_container)
.find("a.tip")
.attr("data-aid", aid)
.on("click", reject)
.end()
.prependTo("#announcement-container");
// *** End of added bit
}
} else {
$('#announcement-container').append("<div> Nothing to show. </div>");
}
}
});
function reject() {
var aid = this.getAttribute("data-aid"); // *** Get the aid from the element
alert("reject aid = " + aid);
}
function fakeAjax(options) {
setTimeout(function() {
options.success({
result: true,
data: [
{id: 1},
{id: 2},
{id: 3}
]
});
}, 300);
}
<div id="announcement-container"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you don't want to change reject
, then just change the handler from:
.on("click", reject)
to
.on("click", reject.bind(null, aid))
and leave the rest the same.