简体   繁体   中英

onclick passing data to javascript

I have a link that when clicked should assign a rails variable to a JavaScript variable. The JavaScript is then used to calculate the price. 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. 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?

You can do the following in jQuery: first add a click hander to the link:

$("a.shirt-color-link").on("click", function(){
   calculatePrice($(this));
})

Then in calculatePrice add argument obj and replace var blankPrice = 5; with:

var blankPrice = obj.attr("data-price");

obj refers to the clicked link and it's 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. 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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM