萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> JQuery基礎語法小結

JQuery基礎語法小結

 在日常開發中JQuery是我們使用最頻繁的JS庫。使用JQuery進行開發,你需要先了解JQuery的基本語法。下面是在學習JQuery時總結的一些簡單語法。

   

1、$(document)將document對象轉換為jquery

 

代碼如下:
$(document).ready(function(){
alert("hello world");
});

 

2、獲取所有的超鏈接對象,並且增加onclick事件;其實在底層jquery對象獲得的每個標簽的數組,因此我們不需要進行循環了

 

代碼如下:
$(document).ready(function(){
$("a").click(function(){
alert("hello world");
});
});

 

3、jquery對象與dom對象之間的轉換

 

代碼如下:
$(document).ready(function(){
var javascriptElement = document.getElementById("clickme");
//將dom對象轉換為jquery對象
var jqueryElement = $(javascriptElement);
//alert("javascript:" + javascriptElement.innerHTML);//innerHTML獲取標簽的內容
//alert("jquery:" + jqueryElement.html());
//將jquery轉換為dom對象方式一
var jElement = $("#clickme");
var javascriptEle = jElement[0];
alert("jquery1: " + javascriptEle.innerHTML);
//方式二
var javascriptEle2 = jElement.get(0);
alert("jquery2: " + javascriptEle2.innerHTML);
});

 

4、jquery解決id值是否存在的問題

 

代碼如下:
<a id="hello">click me</a>
<script type="text/javascript">
//以傳統方式解決id為空方式一
if(document.getElementById("helllo")) {
//如果hello不存在會出錯
document.getElementById("helllo").style.color ="red";
}
//方式二
//$("#hello")[0].style.color="red";
//用jquery解決
$("#hello").css("color","red");
//如果只有一個參數,則此方法是讀,如果是兩個參數則是些功能(css(“”),css(“”,“”))
alert($("#hello").css("color"));
</script>

 

5、在javascript中規定,你要操作css屬性時要將屬性中的‘-'去掉,同時把後一個字母大寫;如:background-color 要改成 backgroundColor

6、jquery中也使用選擇器來操縱各種各樣的元素。是繼承了css的設計理念,但是把它更是發揚光大了;

7、jquery的幾種書寫形式

1> 方式一

 

代碼如下:
$("document").ready(function(){
...
});

 

2> 方式二

 

代碼如下:
$().ready(function(){
...
});

 

3> 方式三

 

代碼如下:
$(function(){
...
});

 

以上幾種方式是一樣的

希望本文所述對大家學習jquery程序設計能有所幫助。

copyright © 萬盛學電腦網 all rights reserved