jQuery中的常用方法:empty()、each()、$.each()、$.trim()、focus()(二)

<!DOCTYPE html>
<html>
  <head>
    <title>02_commonMethod.html</title>
	
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=UTF-8">
    
	<script type="text/javascript" src="js/jquery-1.11.3.js"></script>
	<script type="text/javascript">
    	$(document).ready(function() {
    		$("#btn1").click(function() {
    			// $("#select").empty();
    			// 尝试清空,输入框:input1,input2
    			// 只能remove一次,多次怎么办?用户再次填写!
    			// $("#input1").removeAttr("value");
    			// $("#input1").attr("value", "");
    				
    		});
    		$("#btn2").click(function() {
    			// 也可以用id选择器或者class选择器等去取。
    			// 这里通过一种特殊的方式去取值。          index不可省略,是循环的计数器
    			$("input[type='text']").each(function (index, input) {
					// jQuery中,遍历每次获得的结果是DOM对象,并不是jQuery对象。
    				alert($(input).val());
					alert($(this).val());
				});
    			// 以上便是局部的each方法。
    		});
    		$("#btn3").click(function() {
    			var array = [1, 2, true, "hi"]; // 建立一个数组
    			// 此方法是全局的each方法,需要传入值。 
    			// 同样得到的应该是DOM对象,只不过我们这里传入的数组是js的基础类型数组
    			// 所以这里直接输出了,不用转成jQuery对象!
    			// 这里的i等同上面的index,obj就是实际的对象。
    			$.each(array, function(i, obj) {
    				// alert(obj);
    				// 同样可以使用this来代替
    				alert(this);
    			});
    			$.each($("input[type='text']"), function(i, obj) {
    				// alert(obj);
    				// 同样可以使用this来代替
    				// alert(this);
    				alert($(this).val());
    			});
    			
    		});
    		$("#btn4").click(function() {
    			$("#input2").focus();
    		});
    		$("#btn5").click(function() {
    			var str = $("#input1").val();
    			alert(str.length);
    			alert($.trim(str).length);
    		});
    	});
    </script>
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
	<style>
		.divClass{
			text-align: center;
			 100%;
		}
	</style>
  </head>
  <body>
    <!-- 一些常用的jQuery的方法 -->
	<!-- 
	empty():
	删除匹配的元素集合中所有的子节点  
	
	each():
	以每一个匹配的元素作为上下文来执行一个函数;
	每次执行传递进来的函数时,函数中的this关键字都会
	指向一个不同的DOM元素。
	
	$.each():
	通用遍历方法,可用于遍历对象和数组。
	
	$.trim():
	去掉字符串起始和结尾的空格。
	$.trim("   hello jQuery!   ");去掉字符串起始和结尾的空格。
	
	focus():
	定焦或当前元素获得焦点时,把光标定位到某一个位置,就不用点击鼠标了;
	增强了用户体验。
	 -->
	 <div class="divClass">
    <br>
    <input type="text" id="input1" value="输入框1"><br>
    <input type="text" id="input2" value="输入框2"><br><br>
    <select id="select">
    	<option>Java</option>
    	<option>IOS</option>
    	<option>UI</option>
    </select> 
    <input type="button" value="empty()清空select" id="btn1">
    <br><br>
    <input type="button" value="each()遍历所有输入框的值" id="btn2">
    <br><br>
    <input type="button" value="$.each()遍历数组" id="btn3">
    <br><br>
    <input type="button" value="focus()定焦到输入框2" id="btn4">
    <br><br>
    <input type="button" value="$.trim()输入框中是否空字符串" id="btn5">
    </div>

  </body>
</html>
原文地址:https://www.cnblogs.com/mzywucai/p/11053392.html