使用jquery从data-price获取数据
问题描述:
I have a working code where i output the price using value="" but i need a way to get data from data-price="" so that i can use value="" to store SKUs. Working demo here http://jsfiddle.net/pe2gpp01/21/
What does this code do? It returns fixed price for female for all products. Price changes for Male only.
<div>
<label class="product">Product</label>
<span>
<input name="category" type="radio" value="10" >
<label>Product A</label>
<input name="category" type="radio" value="20" checked>
<label>Product B</label>
<input name="category" type="radio" value="30">
<label>Product C</label>
<input name="category" type="radio" value="40" >
<label>Product D</label>
</span></div>
<div>
<label class="gender">Gender</label>
<span>
<input name="gender" type="radio" value="male" checked>
<label>Male</label>
<input name="gender" type="radio" value="female">
<label>Female</label>
</span></div>
<span>Show Price: <span id="price"></span></span>
<script>
$(function() {
$('[type="radio"]').on('change', function() {
var price = $('[value="female"]')[0].checked
? 10
: $('[name="category"]:checked').val();
$('#price').text(price);
}).change();
});
</script>
I need data from this
<input name="category" type="radio" value="SKU001" data-price="10">
<label>Product A</label>
<input name="category" type="radio" value="SKU002" data-price="20" checked>
<label>Product B</label>
<input name="category" type="radio" value="SKU003" data-price="30">
<label>Product C</label>
<input name="category" type="radio" value="SKU004" data-price="40">
<label>Product D</label>
答
You have to use data
method to get data-price
attribute
$('[name="category"]:checked').data('price')
答
This code is saying if you have a value female element checked, then set the price to 10, otherwise price is the value in named category.
var price = $('[value="female"]')[0].checked
? 10
: $('[name="category"]:checked').val();
... so, this ...
var price = $('[value="female"]')[0].checked
? 10 + parseInt($('[name="category"]:checked').val(),10)
: $('[name="category"]:checked').val();
... will add 10 to the category value (note the user of the parseInt function for proper addition.