How to store field Id in a row?
I write a web site with jquery and lot of ajax request to get data for table and ask data modifications with PHP/MySql on server side.
Currently, I use id attribute to store the id of the field of the table (which is an autoincrement int value).
And it works fine.BUT I have recently learned that id should be unique (and start with a letter...).
AND I have different tables that could have the same id value (for different sql tabl开发者_如何学编程e) Then I am not html (nor xhtml) compliant...How could I correct my code ?
- By using
.data()
function of jQuery ? - An hidden html element with the id as value (
<span class="id">3</span>
) ? - Other solution ?
Additional informations:
I have wrote a widget to manage my tables. To add a new row, I do: row = $('<div class="row" id="'+item.id+'"/>');
[...] // I add fields to my row
row.appendTo(tableData);// tableData is the html element where rows are
When a field element is changed, I trigger an event to the table that will ask the modification to the server with the right id:
$(e.target).closest(".row").attr("id")
If you are able to use jQuery 1.4.3 or greater look at using the html 5 data-*
attributes. jQuery 1.4.3 will automatically use those data- attributes and place them in the .data()
collection on the element.
Example:
<table>
<tr data-rowId="1">
</tr>
</table>
$("tr:first").data("rowId")
would print 1
This method would also allow you to store json objects as well.
<table>
<tr data-row='{"Id" : 1, "Name": "Smith"}'>
</tr>
</table>
And than in your data()
var row = $("tr:first").data("row")
You can reference row.Id
and row.Name
You can prefix your id with the table name :
<div id="mytable_1234"></div>
It's easy to extract the table name and the id from the field and this is HTML compliant.
var values = $(element).attr('id').split('_');
// values[0] is the table name and values[1] is the id.
You can use any other separator if you're already using underscores in your table names.
you can also use jQuery metadata .....
Its awesome to store data in html
Instead of using id
use data-id
and use the .data('id')
(on that element) to retrieve it with jQuery.
I think... I understand your question - multiple data tables, all with autoincrement ids?
My solution would be pre-appending the ID with a letter (like you said) to differentiate it.
Example would be a dataset for 'cars' I would do:
<table>
<tr id="cars_1">
...
</tr>
<tr id="cars_2">
...
</tr>
<tr id="cars_3">
...
</tr>
</table>
Later if you have another table, bikes, you would do:
<table>
<tr id="bike_1">
...
</tr>
<tr id="bike_2">
...
</tr>
<tr id="bike_3">
...
</tr>
</table>
Your end result would be unique ID's while keeping the ID db value in mind, so you would do a simple check (if cars, then do this, etc), then to seperate the prefix (cars from the id 1, you would use something like the PHP expolode()
fn).
Hope that clarifies it, and that I understood your question.
精彩评论