[英]Get Attribute Value From Specific Select Option
选择后如何访问选项中的属性值?
这是我的HTML
<select name="property_id">
<option value="1" price="15000">Property A</option>
<option value="2" price="21000">Property B</option>
</select>
这是我的JS
<script>
$(document).ready(function(){
var $price = $(this).attr('price'),
$percentage = $("input[name='participation_percent']").on("input", calculatePrice),
$discount = $("input[name='participation_amount']").on("input", calculatePerc);
function calculatePrice() {
var percentage = $(this).val();
var price = $price.val();
var calcPrice = ( price * percentage / 100 ).toFixed(2);
$discount.val( calcPrice );
}
function calculatePerc() {
var discount = $(this).val();
var price = $price.val();
var calcPerc = (discount * 100 / price);
$percentage.val( calcPerc );
}
</script>
我想从属性价格中获取价值,但无法正常工作。 任何想法 ?
.val()
是一种jQuery方法,为您提供<input>
的value
属性。
例:
<input value="some-value" id="demo" />
$("#demo").val();
// will return "some-value"
它不会为您提供<input>
属性的值。 从语义上来说,这可能是一个很小的差异,但这是一个重要的差异。
例:
<input value="some-value" id="demo" price="12345" />
$price = $("[price]").val();
// will also return "some-value",
// it doesn't matter you called the var `$price` or that you used
// the `price` attribute to select it from DOM
为了获得任何元素的price
自定义属性值,请考虑您的示例,您应该使用:
<input price="1234" />
$(this).attr('price');
// will return "1234"
*在上面的所有示例中, $(this)
应该是围绕在其之前概述的元素的jQuery
包装器。
选择的选项将随每次更改发送到控制台。 您也可以将其存储在某些变量中以备将来使用。
添加了代码: $("#select").val()
。
注意 :您没有指定希望显示的确切值,所以我添加了两种情况value
和price
。
$(document).ready(function() { var $price = $(this).attr('price'), $percentage = $("input[name='participation_percent']").on("input", calculatePrice), $discount = $("input[name='participation_amount']").on("input", calculatePerc); function calculatePrice() { var percentage = $(this).val(); var price = $price.val(); var calcPrice = (price * percentage / 100).toFixed(2); $discount.val(calcPrice); } function calculatePerc() { var discount = $(this).val(); var price = $price.val(); var calcPerc = (discount * 100 / price); $percentage.val(calcPerc); } }); function getVal() { console.log($("#select").val()); console.log($("#select option:selected").attr('price')); } getVal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="property_id" onchange='getVal()' id='select'> <option value="1" price="15000">Property A</option> <option value="2" price="21000">Property B</option> </select>
$("#select").change(function() { alert($("option:selected", this).attr("data-price")) }).change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="property_id" id='select'> <option value="1" data-price="15000">Property A</option> <option value="2" data-price="21000">Property B</option> </select>
this
上下文 data-*
属性,因为价格不是有效属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.