Reputation: 847
Lately I have gotten into the habit of encoding certain information in my ids. For instance, querying the database
select article_id, title from articles order by ...
and then using PHP to encode the information in the id of an element
foreach($article as $id=>$title){
echo '<span class="title" id="a_'.$id.'">'.$title.'</span><br />';
}
I do this so that I can use javascript/jQuery to grab the id for an ajax call, say to fetch 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 advocated, so I am beginning to wonder if I am setting myself up for some kind of catastrophe.
Upvotes: 5
Views: 236
Reputation: 131
If you're using HTML5 you can use the data attribute.
e.g.
<span class="title" data-id="' . $id . '">'.$title.'</span>
Then you can access it via jQuery like this:
$("span.title").click(function(){
var id = $(this).data('id');
$.ajax({
...
});
});
Upvotes: 2