在变更事件中获取数据属性

问题描述 投票:0回答:1

我正在尝试检索确实添加到option元素的客户数据属性,但是它不起作用。

<p>Select a new car from the list.</p>

<select id="mySelect" onchange="myFunction(this.data-price)">
  <option data-price="250" value="Audi">Audi</option>
  <option data-price="130" value="BMW">BMW</option>
  <option data-price="120" value="Mercedes">Mercedes</option>
  <option data-price="400" value="Volvo">Volvo</option>
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
function myFunction(val) {
  document.getElementById("demo").innerHTML = "You selected: " + val;
  console.log(val);
}

问题是当我将函数调用切换到:

onchange="myFunction(this.value)">

它正确返回了值,但是当我选择数据价格时,它会将undefined返回到控制台。

javascript jquery html javascript-events
1个回答
0
投票

仅访问所选选项的数据属性(因为您标记了它,所以是jQuery示例):

$("#mySelect").change(function() {
    alert($(this).find(':selected').data('price'))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Select a new car from the list.</p>

<select id="mySelect">
  <option data-price="250" value="Audi">Audi</option>
  <option data-price="130" value="BMW">BMW</option>
  <option data-price="120" value="Mercedes">Mercedes</option>
  <option data-price="400" value="Volvo">Volvo</option>
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
© www.soinside.com 2019 - 2024. All rights reserved.