简体   繁体   English

Html 元素获取特定属性值

[英]Html element get specific attribute value

I would like to get the "data-price" attribute from the option element onChange.我想从选项元素 onChange 中获取“数据价格”属性。 getting the value does work, but i can not get the data-price attribute.获取值确实有效,但我无法获取 data-price 属性。 I have the following code, which doesnt work.我有以下代码,它不起作用。

 function getComboA(selectObject) { var printit = selectObject.getAttribute("data-price"); console.log(printit); } /*with this it gets the value tho, but i need the data-price attribute function getComboA(selectObject) { var printit = selectObject.value; console.log(printit); } */
 <select id="comboA" onchange="getComboA(this)"> <option value="">Select combo</option> <option data-price=100 value="Value1">Text1</option> <option data-price=200 value="Value2">Text2</option> <option data-price=2003 value="Value3">Text3</option> </select>

By JavaScript :通过JavaScript

var selection = document.getElementById("comboA");
selection.onchange = function(event){
  var printit  = event.target.options[event.target.selectedIndex].dataset.price;
  console.log(printit);
};

Or JQuery :JQuery

 $('#comboA').change(function(){ var printit =$(this).find(':selected').attr('data-price') console.log(printit); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="comboA" > <option value="">Select combo</option> <option data-price=100 value="Value1">Text1</option> <option data-price=200 value="Value2">Text2</option> <option data-price=2003 value="Value3">Text3</option> </select>

This should make it work:这应该使它工作:

const comboA = document.querySelector('#comboA');
comboA.addEventListener('change', function(event) {
    console.log(event.target.options[event.target.selectedIndex].dataset.price);
});

With this you can also omit the function call in html.有了这个,您还可以省略 html 中的 function 调用。

You can use the selectedIndex of the selectObject to get the index which you can use to get the selected option and then you can get the data-price attribute of that option.您可以使用selectObjectselectedIndex来获取可用于获取所选选项的索引,然后您可以获取该选项的data-price属性。 Code:代码:

function getComboA(selectObject) {
  var selectedIndex = selectObject.selectedIndex;  
  var selectedPrice = selectObject[selectedIndex].getAttribute("data-price");
  console.log(selectedPrice);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM