我试图将data-id
属性值映射到Javascript数组名称。将HTML数据id值赋给Javascript数组名称
我想要product = productid01
其中productid01
是文本值data-id
。
<html>
<table>
<tr>
<td>$200<button type="button" class="function-buy" data-id="productid01" id="btn-productid01">Buy</button></td>
</tr>
</table>
</html>
<script>
$(document).ready(function() {
var productid01 = {desc:"This is a product", price:200.00};
$(document).on('click', '.function-buy', function(){
id = $(this).data("id"); //id = productid01
var product = id; //var product = productid01 (would like !)
document.write(product.desc); //Expected output : This is a product
});
});
</script>
我发现eval()
似乎工作:
var product = eval(id);
,但有没有更好的方式来实现这一目标而无需使用eval()
?
确定我在这里有一种数据类型不匹配,但我无法弄清楚如何解决这个问题。
感谢您的帮助。
这感觉就像是你在思考的事情或有一个行为你没有完全解释。你还试图在点击事件中检索到你还没有使用'eval'? –
因此,您试图根据'data-id'属性的值将产品的ID映射到实际对象?您的产品列表是否以数组形式存储在内存中? –