I am dynamically generating an anchor tag using jQuery. I have added an onclick attribute to it but when I click on the link the onclick does not fire.
I am generating the link as follows:
$(document).ready(function() { var attributes = { 'id': 'xxx', 'onclick': 'alert('xxxx');', 'href': 'https://localhost/widget/TabTest.aspx#' }; var link = $.create('a', attributes); $(link).append('xxxx'); $('#WidgetContainer').append(link); });
Set the click attribute with the jQuery’s click() function.
What you did will likely work in some browsers but not others (I’d had that work in FF but fail in IE). Generally, if jQuery has a function to do something, use it.
EDIT: In response to Adam Backstrom’s comment on the question I figured I’d better offer an alternative. When I’ve done this in the past, I did it like this:
EDIT 2: From the comments to this post, how to do this in one line (not always in the best idea):