[英]How to get the option value in javascript
我有這個代碼:
<SELECT onChange="chData(this,this.value)">
<OPTION VALUE="_MIPS-LRSYSCPU">MIPS
<OPTION VALUE="_XXCEC-LRSYSCPU">% CEC
<OPTION VALUE="_nIFL-LRSYSCPU">nIFL
</SELECT>
我需要使用javascript來獲取HTML PAGE中選項值的所有值(不是文本)。 問題是,知道該值包含單詞“-LRSYSCPU”,但我不知道前一部分(示例_MIPS)。 第二個問題是我在選擇中沒有ID,所以如何獲取選項值? 我見過人們使用這段代碼:
var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
但我沒有身份證,所以我不知道如何繼續..
我需要使用以下三個值創建一個數組:_MIPS-LRSYSCPU,_XXCEC-LRSYSCPU和_nIFL-LRSYSCPU。 謝謝
如果您只在整個頁面上使用單一選擇,那么您可以使用 -
let selectTags = document.getElementsByTagName('select');
然后它會返回你的HTMLCollection數組[select]。 現在,您可以使用selectTags [0]來獲取您的選擇,這是HTMLCollection類型的對象。 該對象包含childNodes 。 迭代子節點將為您提供所有選項和值。
要獲取頁面中包含子字符串“LRSYSCPU”的所有選項值,您可以使用以下代碼:
// Grab all the options in the page const options = document.querySelectorAll('option'); // `filter` out the options that have the "LRSYSCPU" substring // in their values const filtered = [...options].filter(({ value }) => value.includes('-LRSYSCPU')); // Iterate over those filtered options with `map` and return only // the values const values = filtered.map(({ value }) => value); console.log(values);
<select> <option value="temp">temp</option> <option value="_MIPS-LRSYSCPU">MIPS</option> <option value="_XXCEC-LRSYSCPU">% CEC</option> <option value="temp2">temp2</option> <option value="_nIFL-LRSYSCPU">nIFL</option> </select>
文檔
您可以使用document.querySelectorAll()
查找以-LRSYSCPU
結尾的所有選項。 然后,您可以循環遍歷它們並測試它們是否已被選中。
let options = document.querySelector("option[value$=-LRSYSCPU]");
for (let i = 0; i < options.length; i++) {
if (options[i].selected) {
value = options[i].value;
text = options[i].text;
break;
}
}
如果您使用jQuery,它有一個選擇器擴展名:selected
,所以您可以在沒有循環的情況下執行此操作:
var option = $("option[value$=-LRSYSCPU]:selected");
var value = option.val();
var text = option.text();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.