簡體   English   中英

選擇元素中的文字是什么

[英]What is text in select element

我正在嘗試使用以下JavaScript代碼在SELECT查找所有OPTION

var temp = document.querySelectorAll("select");
console.log(temp[0].childNodes);

和html標記是這個

 <select>
    <option>1</option>
    <option>2</option>
 </select>

但這給了我以下Google Chrome瀏覽器中的輸出

在此處輸入圖片說明

那么輸出在每個選項之前出現的文本是什么。

您必須使用select元素的options屬性,

var temp = document.querySelectorAll("select");
console.log(temp[0].options);

childNodes也將為您提供空的文本節點(空格/返回)。 因此建議使用options querySelectorAll ,您可以在獲取的select元素上使用querySelectorAll

var temp = document.querySelectorAll("select");
console.log(temp[0].querySelectorAll("option"));

文本值是您為此獲取的:

 <select id="selectid">
  <option value="volvo">Volvo text</option>  
  <option value="saab">Saab text</option>
  <option value="mercedes">Mercedes text</option>
  <option value="audi">Audi text</option>
 </select> 

現在,如果要所有<option>對象使用此對象:

$("#selectid option").each(function()
{
    //you get "each" option for the select in the id.
});

使用純JavaScript

 function displayResult() {
var x = document.getElementById("selectid ");
var txt = "All options: ";
var i;
for (i = 0; i < x.length; i++) {
    txt = txt + "\n" + x.options[i].text;
}
alert(txt);
 }

你可以試試看

var selects = document.querySelectorAll("select");
var firstSelect = selects[0];
var firstSelectOptions = firstSelect.querySelectorAll("select");
// firstSelectOptions[0].innerText
// firstSelectOptions[0].innerText

Node.childNodes只讀屬性返回給定元素的子節點的實時集合。 childNodes還包括例如文本節點和注釋。 要跳過它們,請改用ParentNode.children 。[ 來自文檔 ]

 var temp = document.querySelectorAll("select"); console.log(temp[0].children); 
 <select> <option>1</option> <option>2</option> </select> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM