I have an requirement of deleting the parent element of an anchor tag. I am adding div and anchor inside it dynamically. below is my code开发者_JAVA技巧, Please help me out
$("<div>"+offer+"<a href='javascript:deleteOrder(this.parent)'>X</a></div>").appendTo($('#resultTable #resultRow td')[selectedOrder-1]);
function deleteOrder(obj)
{
$(obj).parent().remove();
}
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 forjQuery("<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.
精彩评论