JavaScript - Testing jQuery



Test JavaScript Framework Library - jQuery


Reference jQuery

To test a JavaScript library, you need to reference it in your web page.

To reference a library, use the <script> tag with its src attribute set to the URL of the library:

Referencing jQuery

<!DOCTYPE html>
<html>
<head>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"> ;
</script>
</head>
<body>
</body>
</html>


jQuery Description

The main jQuery function is the $() function (jQuery function). If you pass a DOM object to this function, it returns a jQuery object with jQuery functionality added to it.

jQuery allows you to select elements via CSS selectors.

In JavaScript, you can assign a function to handle the window load event:

JavaScript way:

function myFunction()
{
var obj=document.getElementById("h01");
obj.innerHTML="Hello jQuery";
}
onload=myFunction;

The equivalent jQuery is different of:

jQuery method:

function myFunction()
{
$("#h01").html("Hello jQuery");
}
$(document).ready(myFunction);

In the last line of the above code, the HTML DOM document object is passed to jQuery: $(document).

When you pass a DOM object to jQuery, jQuery returns a jQuery object wrapped in an HTML DOM object.

The jQuery function returns a new jQuery object, of which ready() is a method.

Since functions are variables in JavaScript, you can pass myFunction as a variable to jQuery’s ready method.

lampjQuery Returns a jQuery object that is distinct from the passed DOM object.
The properties and methods owned by jQuery objects are different from those of DOM objects.
You cannot use HTML DOM properties and methods on jQuery objects.


Testing jQuery

Please try the following example:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
<script src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script>
<script>
function myFunction(){
	$("#h01").html("Hello jQuery")
}
$(document).ready(myFunction);
</script>
</head>
<body>
	
<h1 id="h01"></h1>

</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance

Please try this example again:

Instance

<!DOCTYPE html>
<html>
<head>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
<script src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script>
<script>
function myFunction(){
	$("#h01").attr("style","color:red").html("Hello jQuery")
}
$(document).ready(myFunction);
</script>
</head>
<body>
	
<h1 id="h01"></h1>
	
</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance

As you can see in the example above, jQuery allows Chaining (chain syntax).

Chaining is a convenient way to perform multiple tasks on the same object.

Need to learn more? PHP Chinese website provides you with a great jQuery tutorial.