1、 jQuery程序的入口
1.1 $(function(){})
1.2 $(element).ready(function(){})
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.min.js"></script>
<script type="text/javascript">
/* $(function() {
alert("01");
}) */
/* $(document).ready(function() {
alert("02");
}) */
/* window.onload = function(){
alert("03");
} */
</script>
注:$即jQuery的简称。
2、hello jQuery
2.1导入js ---> <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
2.2 $(fn)、$(document).ready(fn)与window.onload的区别?(项目维护的时候需要用到)
结论:$(fn)、$(document).ready(fn)是等价的,哪个代码在前面那个代码先执行,jsp的dom树结构加载完毕即刻调用方法;
window.onload最后执行,jsp的dom树加载完,css、js等静态资源加载完毕执行;
3、 jQuery三种工厂方法
3.1 $(exp,[context])
exp:选择器
context:上下文,环境/容器,documemt
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.min.js"></script>
<script type="text/javascript">
/* //标签选择器
$(function() {
$("a").click(function() {
alert("哈哈");
})
}) */
/* //id选择器
$(function() {
$("#a2").click(function() {
alert("哈哈");
})
}) */
/* //类选择器
$(function() {
$(".c1").click(function() {
alert("哈哈");
})
}) */
/* //包含选择器
$(function() {
//$("p a")
//第一个是开始的标签
//第二个是第一个标签里面的标签
$("p a").click(function() {
alert("哈哈");
})
}) */
//组合选择器
$(function() {
$("div,h1").click(function() {
alert("哈哈");
})
})
</script>
3.2 jQuery(html) (demo3.jsp)
html:基于html的一个字符串
3.3 jQuery(element) (demo3.jsp)
element:js对象,表示一个html元素对象
js对象与jquery对象的相互转换
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(":input[name='name1']").click(function() {
//在id=#selId1的select的jQuery实例上追加<option value='1'>湖南省</option>的html jQuery实例
$("#selId1").append("<option value='1'>湖南省</option>");
});
$(":input[name='name2']").click(function() {
//将<option value='1'>湖南省</option>的html jQuery实例追加到id=#selId1的select标签jQuery实例中
$("<option value='1'>长沙市</option>").appendTo("#selId2");
/* var $h1 = $('#h1');
alert($h1.val());
//jQuery对象转js
//第一种(通过集合)
//var h1Node = $h1.get(0);
//第二种(通过数组)
var h1Node = $h1[0];
alert(h1Node.value); */
var h2Node=document.getElementById("h2");
alert(h2Node.value);
//js对象转jQuery对象
var $h2=$(h2Node);
alert($h2.val());
});
})
</script>