$(function(){ $("#mydiv").click(function(){ //從dom到jquery的轉變
var mydiv = document.getElementById("mydiv"); $(mydiv).text("8888"); }); });
$(function(){ $("#mydiv").click(function(){ //document屬於dom的根節點
alert( $(document) ); alert( $(document).text() ); //通過id獲取jQuery對象
alert( $("#mydiv").text() ); //通過class獲取jQuery對象
alert( $(".mydiv").text() ); alert( $(".mydiv").length ); //通過標簽名獲取jQuery對象
alert( $("a").text() ); alert( $("a").length ); //一次獲取多個對象
alert( $("#a1,#a2,#a3").text() ); alert( $("#a1,#a2,#a3").length); //設置文本內容
$("#mydiv").text("你好") ; //text()和html()的差別
alert( $("#mydiv").text() ); alert( $("#mydiv").html() ); $("#a08a").html("<a href='http://www.163.com'>
網易</a>");
//val()方法當set和get使用
alert( $("#mydiv").val() ); $("#mydiv").val('你好呀'); //css()方法
$("#mydiv").css("border","3px dotted blue"); //attr()方法
alert( $("#mydiv").attr('style') ); $("#mydiv").attr('style',"background:green"); $('body').attr("style","padding:0;margin:0"); }); });
$(function(){ $("#mydiv").click(function(){ //舊版本是.size()方法,新版本改為.length
alert( $("div").length ); //index()返回對象所在包裝集的下標,注意index(int)並不會返回對應
坐標的對象 var arrayList = $("div");//返回多個jQuery對象
var oneElement = $("#a02");//返回單一對象
alert ( arrayList.index( oneElement ) ); alert( $(arrayList[1]).text() ); //get或者[]獲出來的是DOM對象
alert( $(arrayList[2]).text() ); alert( $(arrayList.get(2)).text() ); //添加元素
$("body").append($("<a href='#'></a>").text("123")); arrayList.css("background","yellow"); $("a").clone().appendTo(document.body); //not()去掉
$("div").not("#a01,#a02").css("background","green"); //filter()僅保留
$("div").filter("#a01,#a02").css("background","green"); //slice(2,4)取中間
$("div").filter(2,4).css("background","green"); //遍歷
$("#a01,#a02,#a03").each(function(){ alert( $(this).text() ); }); }); });
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript"> $(function(){ $("#a01").click(function(){ //$(a b) //form里面的input
$("form input") .css("border","3px solid blue") .css("background","yellow") .val("ok"); }); $("#a02").click(function(){ //$(a>b) //form里面的input
$("form>input") .css("border","3px solid blue") .css("background","red") .val("子元素"); }); //$(span+input) [同輩,注意返回的是input]
$("#a03").click(function(){ $("span+input").css("background","yellow"); }); $("#a04").click(function(){ $("span~input").css("background","yellow") .hide(); }); }); </script>
</head>
<body>
<form id="frm">
<span>姓名:</span>
<input type="text" value="1">
<div>
<input type="text" value="2">
</div>
<input type="text" value="3">
<input type="text" value="4">
</form>
<input type="text" value="5">
<div id="a01">層次選擇器__$(a b) [后代元素,不管層次]</div>
<div id="a02">層次選擇器__$(a>b) [子元素]</div>
<div id="a03"> 層次選擇器__$(a+b) [緊鄰同輩,注意別看到a+b就認為返回內容是包含a和b2個,返回的是b] </div>
<div id="a04"> 層次選擇器__$(a~b) [相鄰同輩,同輩就行,不需要緊鄰] </div>
</body>