[英]onclick passing data to javascript
I have a link that when clicked should assign a rails variable to a JavaScript variable. 我有一个链接,单击该链接时应将rails变量分配给JavaScript变量。 The JavaScript is then used to calculate the price.
然后使用JavaScript计算价格。 I have the price calculated with a hard coded value at the moment.
我目前已使用硬编码值计算了价格。
in the html I need data-price
to be var blankPrice
in the js. 在html中,我需要
data-price
在js中为var blankPrice
。 Any help would be great. 任何帮助都会很棒。
$("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>
Where is the click handler for the link element? link元素的点击处理程序在哪里?
You can do the following in jQuery: first add a click hander to the link: 您可以在jQuery中执行以下操作:首先向链接添加点击处理程序:
$("a.shirt-color-link").on("click", function(){
calculatePrice($(this));
})
Then in calculatePrice
add argument obj
and replace var blankPrice = 5;
然后在
calculatePrice
添加参数obj
并替换var blankPrice = 5;
with: 有:
var blankPrice = obj.attr("data-price");
obj
refers to the clicked link and it's data-attributes
. obj
指的是单击的链接,它是data-attributes
。
$('.shirt-color-link').attr("data-price", blankPrice);
EDIT - this is changing the "data-price" attribute to be whatever the value of the blankPrice variable is. 编辑-这会将“ data-price”属性更改为blankPrice变量的值。 You might want it the other way round, on reading again (it's a bit unclear), in which case do
您可能希望以另一种方式,再次阅读(这有点不清楚),在这种情况下,
var blankPrice = parseInt($('.shirt-color-link').attr("data-price"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.