當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


HTML DOM Datalist用法及代碼示例


DOM數據列表對象用於表示HTML <Datalist>元素。數據列表元素由getElementById()訪問。

屬性:它具有“選項”屬性,該屬性用於返回數據列表中所有選項值的集合。

用法:

document.getElementById("gfg"); 

其中“gfg”是分配給“Datalist”標簽的ID。

示例1:



<!DOCTYPE html> 
<html> 
  
<body> 
    <center> 
        <h1 style="color:green;font-size:39px;"> 
          GeeksForGeeks 
        </h1> 
        
        <h2>DOM Datalist object</h2> 
    
    <form> 
        <label>Your Cars Name:</label> 
        <input list="gfg"> 
        <datalist id="cars"> 
            <option value="BMW" /> 
            <option value="Bentley" /> 
            <option value="Mercedes" /> 
            <option value="Audi" /> 
            <option value="Volkswagen" /> 
        </datalist> 
    </form> 
    
    <br> 
    <button onclick="myGeeks()">Submit</button> 
  
    <p id="sudo"></p> 
  
    <script> 
        function myGeeks() { 
            var g =  
            document.getElementById("gfg").options.length; 
            
            document.getElementById("sudo").innerHTML =  
              "There are " + g + " options in the list."; 
        } 
    </script> 
</center> 
  
</body> 
  
</html>

輸出:

在單擊按鈕之前:

單擊按鈕後:

示例-2:

<!DOCTYPE html> 
<html> 
  
<body> 
    <center> 
        <h1 style="color:green;font-size:39px;"> 
          GeeksForGeeks 
        </h1> 
  
        <h2>DOM Datalist object</h2> 
  
        <form id="GFG"> 
            <b><label>Your cars name:</label></b> 
        </form> 
        <br> 
  
        <button onclick="myGeeks()">Submit</button> 
  
        <script> 
            function myGeeks() { 
                var g = document.createElement("INPUT"); 
                g.setAttribute("list", "cars"); 
                document.getElementById("GFG").appendChild(g); 
  
                var f = document.createElement("DATALIST"); 
                f.setAttribute("id", "cars"); 
                document.getElementById("GFG").appendChild(f); 
  
                var w = document.createElement("OPTION"); 
                w.setAttribute("value", "BMW"); 
                document.getElementById("cars").appendChild(w); 
  
                var x = document.createElement("OPTION"); 
                x.setAttribute("value", "Mercedes"); 
                document.getElementById("cars").appendChild(x); 
            } 
        </script> 
    </center> 
  
</body> 
  
</html>

輸出:

在單擊按鈕之前:

單擊“打開”按鈕後:

支持的瀏覽器:下麵列出了DOM Datalist Object支持的瀏覽器:

  • 穀歌瀏覽器
  • IE瀏覽器
  • Firefox
  • Opera
  • Safari

相關用法


注:本文由純淨天空篩選整理自ManasChhabra2大神的英文原創作品 HTML | DOM Datalist Object。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。