当前位置: 首页>>代码示例>>用法及示例精选>>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。