我正在尝试检索确实添加到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
返回到控制台。
仅访问所选选项的数据属性(因为您标记了它,所以是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>