Giving my Hyperlinks custom attributes
I would like to give all of my URL's attributes. There are probably about 400 on each page. Sometimes only 40, just depending on which type of product is being viewed.
I would like something like this:
<a href="link.html" class="something" title="Click here to add this to your cart" partno="DBF-XJ3" qtyTy开发者_如何学编程pe="Box QTY" quantity="50">Stainless Steel Bolts</a>
How can this be done?
I know that in HTML5 there is some kind of data thing, but I can't find it yet, so maybe I misread something somewhere.
Basically, when any one of those links are clicked, I will (PHP) insert that product into their shopping cart in the database. But, based on the attributes of any given link, I may need to do some calculations/adjustments/etc before I insert them into the DB.
And this seems like the only simple, logical (and somewhat fun) way to go about doing this. But I'm not sure about compatibility between browsers, or whether it's even valid or not.
You're right, it's the data-
attribute you're looking for. [random reference]
Your link would look something like this:
<a data-partno="DBF-XJ3" data-qtyType="Box QTY" data-quantity="50">
Demo here: http://jsfiddle.net/wesley_murch/ey2pg/
It's really just a javascript hook, and since jQuery seems to handle it well in all browsers I checked (including IE6), I would say its "safe" to use. As far as I know, you can even make up attributes and it will work with jQuery (although it's not recommended). This is really the best way to avoid abusing rel
and title
and such (as a lot of people do), just for javascript interaction.
However: I would highly suggest using a <form>
with hidden <input>
s (and a <button>
for easy styling) to submit the values. The other way is broken without javascript, you can enhance it with jQuery afterwards.
You'd do it like this:
$(document).ready(function(){
$("a[href]").each(function(){
if($(this).attr("href") == "link.html"){ //I put a condition here just in case you need one
$(this).attr({
"partno": "DBF-XJ3",
"qtyType": "Box QTY",
"quantity": "50"
});
}
});
});
If all your links need the same attributes, you can remove the condition.
Hope this helps. Cheers
PS: It will work in every browser, however HTML5 recommends to prepend the 'data-
' prefix to your custom attributes. Example data-partno="DBF-XJ3"
精彩评论