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


HTML DOM button用法及代碼示例


HTML中的按鈕對象用於表示<button>元素。 getElementById()方法用於獲取按鈕對象。

創建按鈕對象:可以使用JavaScript創建按鈕對象。 document.createElement()方法用於創建<button>元素。創建按鈕對象後,使用appendChild()方法附加特定元素(例如div)以顯示它。

範例1:

<!DOCTYPE html>  
<html>  
    <head>  
        <title>  
            DOM Button Object  
        </title>  
          
        <!-- script to create new button -->
        <script>  
            function Geeks() {  
                var myDiv = document.getElementById("GFG");  
                  
                // creating button element  
                var button = document.createElement('BUTTON');  
                  
                // creating text to be 
                //displayed on button 
                var text = document.createTextNode("Button"); 
                  
                // appending text to button 
                button.appendChild(text); 
                  
                // appending button to div 
                myDiv.appendChild(button); ;  
            }  
        </script>  
    </head>  
      
    <body style = "text-align:center;">  
      
        <h1 style = "color:green;">  
            GeeksforGeeks  
        </h1>  
          
        <h2>  
            DOM Button Property  
        </h2>  
          
        <p>Click the button to create a button.</p>  
          
        <button onclick = "Geeks()"> 
            Press me! 
        </button>  
          
        <br><br> 
          
        <div id = "GFG"></div> 
    </body>  
</html>                    

輸出:
在單擊按鈕之前:
buttonobj
單擊按鈕後:
buttonobj

訪問按鈕對象:使用getElementById()方法訪問按鈕對象。將按鈕元素的ID放入getElementById()中以對其進行訪問。



範例2:

<!DOCTYPE html>  
<html>  
    <head>  
        <title>  
            DOM Button Object  
        </title> 
          
        <script> 
        function geek() { 
              
            // Accessing the button element 
            // by using id attribute 
            var doc = document.getElementById("btn"); 
              
            // Changing the text content 
            doc.textContent = "Click me!"; 
        } 
        </script> 
    </head>  
      
    <body style = "text-align:center;">  
      
        <h1 style = "color:green;">  
            GeeksforGeeks  
        </h1>  
          
        <h2>  
            DOM Button Property  
        </h2>  
          
        <p> 
            Click the button to change the  
            text inside it. 
        </p> 
          
        <button type = "button" id = "btn"
            onclick = "geek()"> 
            Try it 
        </button> 
    </body>  
</html>                    

輸出:
在單擊按鈕之前:
buttonobj
單擊按鈕後:
buttonobj




相關用法


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