JavaScript & jQuery 的應用(二):Selector, event, load()

JavaScript & jQuery 的應用(二):Selector, event, load()

Selector

初次接觸jQuery,一開始最讓我驚豔的就是它的Selector了,非常的便利又簡單。除了透過id,連class name,DOM元件本身的屬性等等都可以利用。

例如:

 

<input type="button" id="Employee" value="Show Employee" />

<script type="text/javascript">
$("#Employee")  //利用id
$("input[id=Employee]") //利用DOM & 屬性判斷
</script>

 

不過回傳的物件是jQuery特有物件,所以在處理上和一般直接使用document.getElementById比較不一樣,這點要特別注意。

jQuery Documentation: Selector

註:如果只是單純的選物件來操作,又有確認的id,還是儘量不要使用jQuery來選取物件,因為會加重client的負擔;如果同時有大量資料需要修正,則採用jQuery會顯得方便許多(最後附的程式碼有範例,就是選了刪除按鈕之後,替每個按鈕增加動作)

Event

在前一節有提到,監聽事件的方式可能因為不同的瀏覽器而有不同的支援,但利用jQuery後,就可以解決這種問題。

例如:

// click( fn )

$("#Employee").click(function(){});

這樣就可以替Employee這個button綁定click事件。其它還有很多好用的事件,可以參考jQuery的範例網站。

jQuery Documentation: Event

 

function load()

jQuery也有提供一些自訂的方法,這邊要介紹load的用法。

 

load(url, parameters, callback)

Initiates an Ajax request to the specified URL with optional parameters. A callback function can be specified that’s invoked when the request completes. The response text replaces the content of all matched elements. Parameters

  • url (String) The URL of the server-side resource to which the request is sent.
  • parameters (Object) An object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used.
  • callback (Function) A callback function invoked after the response data has been loaded into the elements of the matched set. The parameters passed to this function are the response text, the status code, and the XHR instance.

 

利用.load(),可以取得其它網頁中的東西來置換目前網頁中的資訊。例如:動態的展現不同的網頁內容,或是讀取某些網頁的特定資訊;而且他還有提供callback function,可操作的便利性更大。

以下範例程式是將網頁中id為Display的div,置換成GridView.aspx中id為Persion的Div,並且為圖片增加刪除列的功能。

			$("#Employee").click
			(
				function()
				{
					$("#Display").load("GridView.aspx #Persion", function()
					{
						$("input[id^='del']").each(function(){$(this).click(function(){$(this).parent().parent().remove()});});
					});
				}
			);

註:網址後面可以增加要選定的內容。

在這邊提供一個小小的範例網站,給大家做參考:jQueryTest.rar

DotBlog 的標籤:,