I'm new to jQuery (1.5 months) and I've found myself developing a PHP + jQuery habit that I don't particularly like. I'm wondering if anyone has suggestions to make things more elegant. Consider the following HTML that I've generated by performing a simple SQL query and echoed with PHP:
<div id='boat_1' class='boat speedboat'></div>
<div id='boat_2' class='boat dory'></div>
<div id='car_1' class='car racecar'></div>
<div id='car_2' class='car racecar'></div>
As you can see, I've opted for an id naming convention that follows {type}_{id}. Now, in jQuery, Assume I want to bind a click handler to these car divs. Remembering that they are dynamic and there could be any number of them, I'd perform:
$(".car").bind('click', function(){
//do something
});
But typically, that //do something would like to know which car fired the click event. Furthermore, that //do something will probably need to seperate the type (boat or car) and the id to perform a POST operation and write back to the database...(for example)
What I'm doing now to find the id (and other unique information as I need it) is simple, but to me, it smells:
$(".car").bind(function(){
var id = $(this).attr("id").replace("car_", "");
});
One might suggest to use the class attribute instead because you don't have to worry about uniqueness. But because class names are not singular (there can be more than one per element as I've shown), I don't see this as a candidate solution.
Because id's must be unique in the entire document, this is the solution I've settled for. I'm aware getElementById() would break if multiple ids of the same name were made possible but sometimes I wonder if it would be beneficial if ids didn't have to be unique provided they have different parents.
How do you do it?
Should I use HTML5's data-*?
Thanks!