Overview
Your best bet here is to create an object or Map
with the things you want to look up this way, and then put them on it as properties or entries.
With an object:
var items = {
product101: {category: "cars"}
};
or if you want to be paranoid about the default inherited properties that exist on objects, you might use an object with no prototype:
var items = Object.create(null);
items.product101 = {category: "cars"};
then in your click handler:
alert(items[pro].category);
Live Example:
$('[data-my-product]').click(function() {
var pro = $(this).data('my-product');
alert(items[pro].category);
});
<div class="container">
<script>
var items = {
product101: {category: "cars"}
};
</script>
<div data-my-product="product101">
//all the product stuff
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
With a Map
:
var items = new Map([
["product101", {category: "cars"}]
]);
then in your click handler:
alert(items.get(pro).category);
Live Example:
$('[data-my-product]').click(function() {
var pro = $(this).data('my-product');
alert(items.get(pro).category);
});
<div class="container">
<script>
var items = new Map([
["product101", {category: "cars"}]
]);
</script>
<div data-my-product="product101">
//all the product stuff
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Side note: Although you can access that data-*
attribute's value (indirectly) using data
, doing so sets up a data cache for the element and initializes that cache with the attribute's value. If you're just looking to get the string, .attr("data-my-product")
is more direct. See this answer for more details.