jQuery each中的this

使用

$.each(function(){

alert(this.nodeName);

alert($(this));

});

要注意二者的不同this是一个dom对象,要使用jQuery的方法必须用jQuery(this)包含,负责只能用dom对象的方法,看下面的例子

<html>
	<head>
		<title>nth-child-test</title>
		<script src="jquery-1.6.1.min.js"></script>
		<script type="text/JavaScript">
			$(function(){
				$("tr").each(function(){
					$(this.nodeName+":nth-child(2)").attr("style","color:red;");	
				});	
			});
		</script>
	</head>
	<body>
		<table>
			<tr>
				<td>1</td>
				<td>1</td>
				<td>1</td>
			</tr>
			<tr>
				<td>2</td>
				<td>2</td>
				<td>2</td>
			</tr>
			<tr>
				<td>3</td>
				<td>3</td>
				<td>3</td>
			</tr>
		</table>
	</body>
</html>
<html>
<head>
<title>jQuery nth-child example</title>
 
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
</head>
 
<body>
 
<h1>jQuery nth-child example</h1>
 
<table border=1>
	<tr><td>Row #1</td></tr>
	<tr><td>Row #2</td></tr>
	<tr><td>Row #3</td></tr>
	<tr><td>Row #4</td></tr>
	<tr><td>Row #5</td></tr>
	<tr><td>Row #6</td></tr>
	<tr><td>Row #7</td></tr>
	<tr><td>Row #8</td></tr>
	<tr><td>Row #9</td></tr>
	<tr><td>Row #10</td></tr>
</table>
<br/>
 
<button>:nth-child(4)</button>
<button>:nth-child(3n)</button>
<button>:nth-child(even)</button>    
<button>:nth-child(odd)</button>
 
 
<script type="text/javascript">
    $("button").click(function () {
      var str = $(this).text();
      $("tr").css("background", "white");
      $("tr" + str).css("background", "coral");
    });
</script>
 
</body>
</html>

相关推荐