Error creating jQuery element?

$ (document) .ready (function () {var _new_li = $ ('', {'id': 'p', 'text': 'CLICKME', click: function () {warning ('fired');} ,
        data: {"somedata": "somedata",}
      });

_new_li.appendTo($("#example"));
});

I get " Uncaught TypeError: cannot read the 'click' of undefined property " when I try to click on an element that I created like this. But, if you switch click: and data: it works.

$(document).ready(function(){
    var _new_li     = $('<li/>',     {
      'id':     'p',
      'text':   'CLICKME',
      data:     {
          'somedata':  'somedata',
      },
      click:    function(){
          alert('fired');
      }                      
    });

_new_li.appendTo($("#example"));
});

any explanation for this behavior?

Yours faithfully

- Andy

PS:

I posted a similar behavior earlier on the jQuery Core Development forum, Mr. Swedberg replied there:

, , , > ( 1.4.2) . , jQuery , , jsbin 1.4. > 1.4.2 , .

, 1.4.2

+5
4

.

( ) .

-, :

$(document).ready(function(){
    var fun=function(){
          alert('fired');
      };
    var parms={
      'id':     'p',
      'text':   'CLICKME',     
      'click':fun,         
      'data':     {
          'somedata':  'somedata'
      }
      };
      console.log(parms);
    var _new_li = $('<li/>',parms);

_new_li.appendTo($("#example"));
});

, li. e is undefined (jquery line 55). , .

jquery, 1919

var events = jQuery.data(, "" ), = [ event.type];

undefined.

jquery , .

. .

.

+5

.. .. ,

.click( [ eventData ], handler(eventObject) )

eventDataA , .

, , jQuery.bind().. "" javascript..

( http://api.jquery.com/bind/):

eventData . , . , . , , , :

var message = 'Spoon!';
$('#foo').bind('click', function() {
  alert(message);
});
message = 'Not in the face!';
$('#bar').bind('click', function() {
  alert(message);
});

- , , " "! . . , eventData:

var message = 'Spoon!';
$('#foo').bind('click', {msg: message}, function(event) {
  alert(event.data.msg);
});
message = 'Not in the face!';
$('#bar').bind('click', {msg: message}, function(event) {
  alert(event.data.msg);
});

; eventData, . Spoon! !

+2

, .

handle: function( event ) {
...

// tbn modified source
try {
   var events = jQuery.data(this, "events"), handlers = events[ event.type ];
} catch(e) {}
// tbn modified source

..

, ().

+1

, , . , mouseout, click .., LI. "Uncaught TypeError: " mouseout " undefined". , , , .. , DOM. , . :

newLI = $('<li />');
$(document.body).append(newLI); // Correct
newLI.click(...);
newLI.mouseout(...);

newLI = $('<li />');
newLI.click(...);
newLI.mouseout(...);
$(document.body).append(newLI); // Incorrect
0

All Articles