Domanda

I want to add some additional properties to table rows. The table is created on the fly, from data returned from the server

The table defined on the HTML:

Then, let's assume I've some json data from the server (data simplified):

people = [{name:"John Doe", person_id:"1234"}, {name:"Jane Roe", person_id:"5678"}]

I now fill up the table with the following code (in my ajax.done handler):

for( i=0; i<people.length; ++i ) {
    var person = people[i];
    var row = $('<tr><td>' + person.name + '</td></tr>');
    row.person_id = person.person_id;      // <<=== HERE I'm trying to add the expando
    row.click( clickHandler );
    $('#myTable > tbody').append(row);
}


function clickHandler( ev ) {
    row = ev.currentTarget;               // This is fine
    id = ev.currentTarget.person_id       // HERE unable to get my expando
}

I'm almost certain that with plain HTML objects (i.e. document.createElement('TR'), without any JS, as well as with Javascript objects, this syntax is working. with jQuery something else is going on.

(Note, there are many ways to workaround it, but for education purposes I really want to know specifically how to work with expandos and jQuery).

È stato utile?

Soluzione

You are setting person_id on jQuery collection object, not the DOM element. The jQuery equivalent is row.prop('person_id', person.person_id);.

That said, to preserve random bits of data along with a DOM element you should use attr() or data()

Altri suggerimenti

This

row.person_id = person.person_id; 

should be

row[0].person_id = person.person_id; 

row is jquery wrapper, but row[0] is DOM Element.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top