Javascript Html元素获取特定属性值
我想从option元素onChange中获取“data price”属性。获取值确实有效,但我无法获取数据price属性。我有下面的代码,它不工作 函数getComboA(选择对象){ var printit=selectObject.getAttribute(“数据价格”); console.log(打印); } /*通过这个函数,它得到值tho,但我需要数据price属性 函数getComboA(selectObject){ var printit=selectObject.value; console.log(打印); } */Javascript Html元素获取特定属性值,javascript,html,Javascript,Html,我想从option元素onChange中获取“data price”属性。获取值确实有效,但我无法获取数据price属性。我有下面的代码,它不工作 函数getComboA(选择对象){ var printit=selectObject.getAttribute(“数据价格”); console.log(打印); } /*通过这个函数,它得到值tho,但我需要数据price属性 函数getComboA(selectObject){ var printit=selectObject.value;
选择组合
文本1
文本2
文本3
通过JavaScript:
var selection = document.getElementById("comboA");
selection.onchange = function(event){
var printit = event.target.options[event.target.selectedIndex].dataset.price;
console.log(printit);
};
或JQuery:
var selection = document.getElementById("comboA");
selection.onchange = function(event){
var printit = event.target.options[event.target.selectedIndex].dataset.price;
console.log(printit);
};
$('#comboA')。更改(函数(){
var printit=$(this).find(':selected').attr('data-price'))
console.log(打印);
});代码>
选择组合
文本1
文本2
文本3
这应该可以让它工作:
const comboA = document.querySelector('#comboA');
comboA.addEventListener('change', function(event) {
console.log(event.target.options[event.target.selectedIndex].dataset.price);
});
这样,您还可以省略html中的函数调用。您可以使用selectObject
的selectedIndex
来获取可用于获取所选选项的索引,然后可以获取该选项的数据价格
属性。
代码:
这回答了你的问题吗?