目录
-
操作文本
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="../js/jquery-3.4.1.min.js"></script> </head> <body> <p>春眠不觉晓,处处闻啼鸟</p> <p>夜来风雨声,花落知多少</p> <input type="text" value="雷猴啊" /> <script> /** * html() ---> innerHTML * text() ----> innerText * val() ---->value --- 应用于表单的 */ /** * 获取文本 */ var content = $("p").html() console.log(content) console.log($("input").val()) /** * JQ中的行为是获取和设置集于一身的 * 设置 * html(内容) * text(内容) * val(内容) */ // $("p").html("我是由JQ给设置的") //$("p").html("<b>我是由JQ给设置的</b>") // 识别标签 //$("p").text("<b>我是由JQ给设置的</b>") // 不识别 $("input").val("123") /** html(function(index, curcontent){ return 设置的新文本 }) text(function(index, curcontent){ return 设置的新文本 }) val(function(index, curcontent){ return 设置的新文本 }) * * index -- 根据选择器查找到的元素对应的索引 * curcontent --- 当前元素中的内容 */ $("p").text(function(index, curcontent){ return index == 1 ? "我是清空内容 新增加的" : curcontent + " 我是追加的" }) </script> </body> </html>
-
操作属性
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> #page{ height: 100px; background-color: palegoldenrod; border: solid 2px plum; } .bin{ border-radius: 20px; } </style> <script src="../js/jquery-3.4.1.min.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div title="我是一个div"></div> <script> /** * 设置属性 * 设置一个属性 * $(选择器).attr(属性名,属性值) * 设置多个属性 * $(选择器).attr({key:value, key:value...}) */ //$("div").attr("id", "page") $("div").attr({ id:"page", class:"bin" }) /** * 获取属性 * $(选择器).attr(属性名) */ console.log($("div").attr("title")) </script> </body> </html>