从特定选择选项获取属性值

时间:2017-02-23 13:45:46

标签: javascript jquery attributes

当我选择它时,如何在选项中访问属性值?

这是我的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>

我想从属性价格中获取价值,但它不起作用。 有什么想法吗?

2 个答案:

答案 0 :(得分:1)

每次更改都会将选择的选项发送到控制台。您也可以将其存储在某个变量中以备将来使用。

添加了代码:$("#select").val()

注意:您没有指定预期显示的确切值,因此我添加了两个案例 - valueprice

&#13;
&#13;
$(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();
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

&#13;
&#13;
GetById(...)
&#13;
$("#select").change(function() {


  alert($("option:selected", this).attr("data-price"))

}).change()
&#13;
&#13;
&#13;

  1. 使用<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>上下文
  2. 使用this属性,因为价格不是有效属性