Home > Web Front-end > JS Tutorial > Using JavaScript to operate a table, you can add rows and columns and change the background color every other row.

Using JavaScript to operate a table, you can add rows and columns and change the background color every other row.

高洛峰
Release: 2016-11-25 15:05:50
Original
962 people have browsed it

<html> 
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 
        <title>JavaScript</title> 
    </head> 
    <body> 
        <script language="javascript"> 
            var n = 0; 
            function showTable(len) { 
                wi(&#39;<table border="1" width="300" style="border-collapse:collapse"><tbody id="table">&#39;); 
                for (i=0;i<len;i++) { 
                    if (parseInt(i%2)==1) { 
                        bg = &#39;#F4FAC7&#39;; 
                    } else { 
                        bg = &#39;white&#39;;    
                    } 
                    wi(&#39;<tr bgcolor=&#39;+bg+&#39;><td>第&#39;+(i+1)+&#39;行</td></tr>&#39;);  
                } 
                wi(&#39;</tbody></table><br />&#39;); 
                wi(&#39;<input type="button" value="Add" id="add" />&#39;);    
            } 
             
            function wi(str) { 
                return document.write(str);  
            } 
            showTable(10); 
             
            var add = document.getElementById("add"); 
            add.onclick = function() { 
                n = n+1; 
                if (n%2==0) { 
                    bg = &#39;#F4FAC7&#39;; 
                } else { 
                    bg = &#39;white&#39;;    
                } 
                var table = document.getElementById("table"); 
                var tr = document.createElement("tr"); 
                tr.bgColor = bg; 
                var td = document.createElement("td"); 
                td.innerHTML = &#39;第&#39;+(10+n)+&#39;行&#39;; 
                tr.appendChild(td); 
                table.appendChild(tr); 
            } 
        </script> 
    </body> 
</html>
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template