JavaScript - Te...LOGIN

JavaScript - Testing jQuery

Reference jQuery

To test the 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 library's URL:

<!DOCTYPE html>
<html>
<head>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js">//Quote here
</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:

Using JavaScript

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

Use jQuery

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.

Note:


jQuery returns a jQuery object, which is different 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.


#Example comparison:

<!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>

Contrast
##

<!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").attr("style","color:red").html("Hello jQuery")
}
$(document).ready(myFunction);
</script>
</head>
<body>
<h1 id="h01"></h1>
</body>
</html>

As you can see in the above example, jQuery allows links (chaining grammar).

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


Next Section

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ alert($("#runoob").attr("href")); }); }); </script> </head> <body> <p><a href="http://www.php.cn" id="runoob">php.cn</a></p> <button>显示 href 属性的值</button> </body> </html>
submitReset Code
ChapterCourseware