4

I create a anchor using jQuery and the onclick event seems be triggered when the element is created. I've used this method of creating elements a few times with this project without a problem, have I got the wrong end of the stick?

jQuery('<a/>', {
    href: '#',
    name: 'link_html_edit',
    id: 'link_html_edit',
    html: 'input HTML text',
    onclick: alert('test')
}).appendTo(spanDefaultValue);

Thanks

3 Answers 3

8

Looking at the jQuery documentation on this page you should be doing this:

$("<a/>", {
   href: '#',
    name: 'link_html_edit',
    id: 'link_html_edit',
    html: 'input HTML text',
  click: function(){
     alert('test');
  }
}).appendTo("body");
Sign up to request clarification or add additional context in comments.

Comments

6

You're calling alert('test'); and assigning it's return value to onclick. Use this instead:

onclick: function(){ alert('test'); }

Since I'm sure alert('test') is just an example I should also point out that if you have the same problem with some function you likely can just change your code from:

onclick: somefunction()

To:

onclick: somefunction

You only need to wrap it in an anonymous function the way I did with alert('test'); if you're passing arguments to the function other than the event object that is normally passed to an event handler.

1 Comment

facepalm didn't think of that thank you. I will accept in T minus 11 minutes
5

This is much better alternative

$("<a/>", {
   href: '#',
    name: 'link_html_edit',
    id: 'link_html_edit',
    html: 'input HTML text'
}).bind('click',function(){ // your function}).appendTo("body");

1 Comment

I get this error with that example: Uncaught DOMException: Failed to execute '$' on 'CommandLineAPI': '<a/>' is not a valid selector. at <anonymous>:1:1 Seems sensible though...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.