I would change how you implement this:
var a = $("<a>").attr("href", "#").addClass("offer");
$("<div>").text(offer).append(a).appendTo("#resultTable");
with:
$(function() {
$("a.offer").live("click", function() {
$(this).closest("div").remove();
return false;
});
});
You're using jQuery but you're inlining your Javascript. This is very "un-jQuery", which instead encourages unobtrusive Javascript. I've used live()
to handle binding that event handler to dynamically created elements. This is (imho) a far cleaner solution.
Also, you can create markup the way you are but it can be problematic. For example, what if offer
includes a <
? Or something else that needs to be escaped? It's better to use functions suited to the job that take of all escaping for you (as I've done). Also, certainly in jQuery 1.4+ and possibly earlier, $("<a>")
is much faster than full markup as the above uses document.createElement()
rather than innerHTML
, which can be really slow on some browsers.
From jQuery 1.4 Released – Full Release Notes:
jQuery(“<div>”) jQuery(“<div/>”) and jQuery(“<div></div>”)
All three now use the same code path
(using document.createElement
),
improving performance for
jQuery("<div></div>")
. Note that if
you specify attributes, we use the
browser’s native parsing (using
innerHTML).
Lastly, you can pass a selector to appendTo()
. No need to pass it a jQuery object.