Should I refrain from encoding information in id attribute

Recently, I'm used to coding certain information in my identifiers. For example, a database query

select article_id, title from articles order by ... 

and then using PHP to encode the information in the id of the element

 foreach($article as $id=>$title){ echo '<span class="title" id="a_'.$id.'">'.$title.'</span><br />'; } 

I am doing this so that I can use javascript / jQuery to grab the id for an ajax call, say to get a preview or something

 $("span.title").click(function(){ var idArr = $(this).attr('id').split('_'); data = {}; data.id = idArr[1]; $.ajax({ ... }); }); 

I have never seen this method supported, so I'm starting to wonder if I'm not tuned in to some kind of disaster.

+4
source share
1 answer

If you are using HTML5, you can use the data attribute.

eg.

 <span class="title" data-id="' . $id . '">'.$title.'</span> 

Then you can access it through jQuery as follows:

 $("span.title").click(function(){ var id = $(this).data('id'); $.ajax({ ... }); }); 
+2
source

All Articles