jquery而不是javascript

时间:2017-03-12 10:36:29

标签: javascript jquery

$(document).ready(function() {
    				var table = document.getElementById("tab");
    				table.style.borderCollapse = "collapse";
    				var rows = table.rows;
    				
    				for(i = 0; i < rows.length; i++) {
    					if(i % 2 == 0) {
    						rows[i].style.backgroundColor = "red";
    					}
    				}
    			});
<html>
       
       <head>
    		<title>JJJJS</title>
    		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
       </head>
       
       <body>
    		<table id="tab">
    			<tr>
    				<td>1</td>
    				<td>2</td>
    				<td>3</td>
    			</tr>
    			
    			<tr>
    				<td>4</td>
    				<td>5</td>
    				<td>6</td>
    			</tr>
    			
    			<tr>
    				<td>7</td>
    				<td>8</td>
    				<td>9</td>
    			</tr>
    		</table>
    	
       
    	  
       </body>
    </html>

它正在工作,但是如何仅使用jQuery实现类似的结果?我试图使用像$("#tab");这样的东西,但它不适合我。哪里弄错了?我的意思是我要为i%2 == 0行着色。

@edit:

例如它不起作用

<script>
            $(document).ready(function() {
                var table = $("#tab");
                table.css("border-collapse", "collapse");
                var rows = table.rows;

                for(i = 0; i < rows.length; i++) {
                    if(i % 2 == 0) {
                        rows[i].style.backgroundColor = "red";
                    }
                }
            });
        </script>

1 个答案:

答案 0 :(得分:0)

试试这个:

<html>
       
       <head>
    		<title>JJJJS</title>
    		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
       </head>
       
       <body>
    		<table id="tab">
    			<tr>
    				<td>1</td>
    				<td>2</td>
    				<td>3</td>
    			</tr>
    			
    			<tr>
    				<td>4</td>
    				<td>5</td>
    				<td>6</td>
    			</tr>
    			
    			<tr>
    				<td>7</td>
    				<td>8</td>
    				<td>9</td>
    			</tr>
    		</table>
    	
       
    	  
       </body>
    </html>
func()
function func (){
alert('alert')
}