Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant get jQuery( html, props ) work with events

Tags:

jquery

I am unable to get the click event to work for elements created thusly.

http://jsfiddle.net/iambriansreed/PEZXa/

jQuery

$('<a href="#">a</a>', {
  click: function(){
    alert('a clicked');
  }
}).appendTo("div");

$('<span>span</span>', {
  click: function(){
    alert('span clicked');
  }
}).appendTo("div");

Please don't show me the 50 different ways you can add an onclick event to an element I want to know why this particular method does or does not work.

From the docs: http://api.jquery.com/jQuery/#jQuery2

like image 678
iambriansreed Avatar asked Dec 02 '22 21:12

iambriansreed


2 Answers

$('<a />', {
    href: '#',
    text: 'a',
  'click': function(){
    alert('a clicked');
  }
}).appendTo("div");

$('<span />', {
    text: 'span',
  'click': function(){
    alert('span clicked');
  }
}).appendTo("div");

http://jsfiddle.net/PEZXa/56/

From the docs

html - A string defining a single, standalone, HTML element (e.g. <div/> or <div></div>).

like image 179
Steve Robbins Avatar answered Dec 04 '22 11:12

Steve Robbins


jQuery doesn't seem to like it when elements that are created like this contain text nodes or attributes. In essence, the HTML code you provide should be a single (possibly self-closing) tag.

This is probably because you are using a syntax that expects the attributes to be defined within the object parameter, not mixed between the HTML and the object.

Anyways, this code works for me:

$('<a /> ', {
    href: '#',
    text: 'a',
    click: function() {
        alert('a clicked');
    }
}).appendTo("div");

$('<span />', {
    text: 'span',
    click: function() {
        alert('span clicked');
    }
}).appendTo("div");​

Demo: http://jsfiddle.net/PEZXa/60/

like image 29
Blender Avatar answered Dec 04 '22 09:12

Blender