不确定标题是否有意义,但是,我想通过click事件发送数据,此click事件将从预设的var(在本例中为product101)获取数据,因为此var格式为JSON,我无法似乎在检索数据,它总是返回未定义的。因为var是一个对象,但是当我使用数据集时var是一个字符串吗?
// inside a loop
<div class="container">
<script> var product<?=$id?> = {"category":"cars"}</script>
<div data-my-product="product<?=$id?>">
//all the product stuff
</div>
</div>
//located in the footer
$('[data-my-product]').click(function(){
//demo
var pro = $(this).data('my-product');
alert(pro.category);//returns undefined
})
当我单击产品时,它会返回“未定义”警报消息。
请注意,产品是在循环内生成的。
答案 0 :(得分:1)
您最好的选择是用您要以此方式查找的对象创建对象或Map
,然后将其作为属性或条目放置在对象上。
var items = {
product101: {category: "cars"}
};
或者如果您想对对象上存在的默认继承属性抱有偏执,则可以使用没有原型的对象:
var items = Object.create(null);
items.product101 = {category: "cars"};
然后在您的点击处理程序中:
alert(items[pro].category);
实时示例:
$('[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>
Map
:var items = new Map([
["product101", {category: "cars"}]
]);
然后在您的点击处理程序中:
alert(items.get(pro).category);
实时示例:
$('[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>
旁注:尽管您可以使用data
(间接)访问data-*
属性的值,但这样做会为元素设置数据缓存并使用初始化该缓存属性的值。如果您只是想获取字符串,则.attr("data-my-product")
更直接。有关更多详细信息,请参见this answer。