jQuery常用语法
2018年4月23日星期一
使用<scriptsrc="../js/jquery-1.12.4.js"></script>引入jQuery 的库文件
$() 工厂函数 将DOM对象转化为jQuery对象
selector 选择器 获取需要操作的DOM元素
action()方法 jQuery中提供的方法包含了绑定事件的处理方法
JQuery对象.addClass()方法为元素添加样式类
css() 方法设置元素样式
show() 、hide()方法设置元素的显示和隐藏
$ 等同于 jQuery
弹出窗口示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JQuery 语法一</title>
</head> <body> <script src="../js/jquery-1.12.4.js"></script> <script> $(document).ready(function () { alert("弹出提示语句!") }); $(document).ready(function () { alert("再次弹出!") }) </script> </body> </html> |
JQuery addClass方法示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jQuery 语法二</title> <style type="text/css"> li{list-style: none; line-height: 22px; cursor: pointer;} .current{background: #6cf; font-weight: bold; color: #fff;} </style> <script src="../js/jquery-1.12.4.js"></script> </head> <body> <ul> <li id="current">jQuery简介</li> <li id = "current2">jQuery语法</li> <li>jQuery选择器</li> <li>jQuery事件与动画</li> <li>jQuery方法</li> </ul> <script> $(document).ready(function () { //点击li的事件 $("li").click(function () { //使用选择器去选择了current样式使用addClass添加 $("#current").addClass("current"); $("#current2").addClass("current"); }) }) </script> </body> </html> |
JQuery css方法示例:
css(“属性”,“属性值”) 单个CSS属性
css({"属性1":"属性1值" ,"属性2": "属性2值"}); 多个CSS属性
$(this).children("当前标签下的标签").show(); //显示
$(this).children("当前标签下的标签").hide(); //隐藏
示例1:
$(document).ready(function () { $("li").mouseover(function () { //鼠标移动到li //改变当前li //设置单个css属性 $(this).css("background","black"); //显示li下面的div $(this).children("div").show(); }).mouseout(function () { //鼠标离开li变回 $(this).css("background","#c81623"); //收回li下面的div $(this).children("div").hide(); }) }); |
示例2:
$(document).ready(function () { $("li").mouseover(function () { //鼠标移动到li $(this).css({"background": "black" ,"font-size": "20px"} ); }).mouseout(function () { //鼠标离开li变回 $(this).css({"background": "#c81623" ,"font-size": "14px"} ); }) }); |
链式操作:对一个对象进行多重操作,并将操作结果返回给该对象
next();取回匹配选择器的下一个同胞元素
隐式迭代 在jQuery中设置集合的属性,不需要遍历每一个元素,可以直接设置
示例:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>隐式迭代</title> <style type="text/css"> li {line-height:22px;} </style> <script src="../js/jquery-1.12.4.js"></script> </head> <body> <ul> <li>数码产品</li> <li>家用电器</li> <li>妇幼保健</li> <li>时尚丽人</li> </ul> <script> $(document).ready(function() { $("li").css({"font-weight":"bold","color":"red"}); }); </script>
</body> </html> |