我正在尝试检索确实添加到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
返回到控制台。
答案 0 :(得分:2)
您的代码说的是“获取数据属性”,并从中减去变量“ price”。第二个问题,您选择的属性上时,住在选项中进行选择。您不能将其像价值一样使用。
您应该在所选选项上使用dataset
function myFunction(sel) {
var opt = sel.options[sel.selectedIndex];
var price = opt.dataset.price
document.getElementById("demo").innerHTML = "You selected: " + price;
}
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction(this)">
<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>
答案 1 :(得分:0)
只需访问所选选项的data属性(由于您已对其进行标记,因此它是jQuery示例):
$("#mySelect").change(function() {
const $this = $(this); // Cache $(this)
const dataVal = $this.find(':selected').data('price'); // Get data value
const selectedVal = $this[0].value;
alert(`${dataVal}, ${selectedVal}`);
});
<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>