我有一个链接,单击该链接时应将rails变量分配给JavaScript变量。然后使用JavaScript计算价格。我目前已使用硬编码值计算了价格。
在html中,我需要data-price
在js中成为var blankPrice
。任何帮助都会很棒。
$("a.shirt-color-link").on("click", function(){
calculatePrice($(this));
})
function calculatePrice(){
var blankPrice = obj.attr("data-price");
console.log(blankPrice)
var pricePerSide = 3;
var printedSides = 0;
if (frontCanvas) {
var frontCanvasJson = JSON.parse(frontCanvas);
if (frontCanvasJson && frontCanvasJson.objects.length > 0)
printedSides++;
}
if (backCanvas) {
var backCanvasJson = JSON.parse(backCanvas);
if (backCanvasJson && backCanvasJson.objects.length > 0)
printedSides++;
}
var total = blankPrice + (pricePerSide * printedSides);
$('.base-price').text('$' + total);
}
<a
tabindex="-1"
data-original-title="<%= shirt_color.color_name.titleize %>"
class="shirt-color-link"
data-color="#<%= shirt_color.hex %>"
data-price="<%= product.base_price %>"
data-product-id="<%= product.id %>">
</a>
最佳答案
link元素的点击处理程序在哪里?
您可以在jQuery中执行以下操作:首先向链接添加点击处理程序:
$("a.shirt-color-link").on("click", function(){
calculatePrice($(this));
})
然后在
calculatePrice
中添加参数obj
并将var blankPrice = 5;
替换为:var blankPrice = obj.attr("data-price");
obj
是指单击的链接,它是data-attributes
。