tags:

views:

1744

answers:

2

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);
});
+4  A: 

Set the click attribute with the jQuery's click() function.

var attributes = {
     "id": "xxx",
     "href": "https://localhost/widget/TabTest.aspx#"
 };
 var link = $.create("a", attributes);
 $(link).append("xxxx").click(function(){ alert("HELLO"); });
 $("#WidgetContainer").append(link);

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:

$("#someplace").wrapInner("<a href='#'></a>");
$("#someplace a").click(function() {
    alert("Hello");
});


EDIT 2: From the comments to this post, how to do this in one line (not always in the best idea):

$("<a id='xxx' href='https://localhost/widget/TabTest.aspx#'&gt;xxxx&lt;/a&gt;")
      .click(function() { alert("Hello"); })
      .appendTo($("#WidgetContainer"));
acrosman
Worked like a charm! thanks.
Si Keep
Long live the overly-terse jQuery; there is almost always a way to write it entirely on one line (whether you should or not):$("<a id='xxx' href='https://localhost/widget/TabTest.aspx#'>xxxx</a>").click(function() { alert("Hello"); }).appendTo($("#WidgetContainer"));
patridge
+1  A: 

If you're using jQuery 1.3 or above, you could use "live" event binding to attach the click event to any <A> tags you add to your page. E.g.:

$('a').live('click', function (evt) {
    alert('Hello');
    evt.preventDefault();
});
var link = $.create('a', {
    'id' : 'xxx',
    'href' : 'http://localhost/'
});
$('#container').append(link);
Andrew Hedges