There are several uses of $() in jQuery

jQuery's $() has 3 methods.

(1) DOM selection, you can specify the context;

(2) DOM creation, you can specify the document, attribute, event, and even all jQuery methods to which it belongs;

(3) DOM loading completion event monitoring is  a simplified way of writing $(document).ready()  .

 

(1) DOM selection

Select by selector:

 

jQuery( selector [, context ] )

 The second optional parameter can specify the context, which can be either a DOM object or a jQuery object. For example, find all li under ul.

 

 

$ul = $('ul');
$ li = $. ('li', $ ul);

 Equivalent to this function:

$li = $ul.find('li');

 (2) DOM creation

Using jQuery to create DOM is also a common operation, such as creating a li under ul:

// method declaration
jQuery( html [, ownerDocument ] )
// example
$('<li>').appendTo($ul);

 Note the second optional parameter, the default value is the Document that is currently loaded with jQuery. Document must be specified if you wish to create an element in an IFrame.

 

When creating a DOM element, in addition to specifying document, you can also specify element attributes:

// method declaration
jQuery( html, attributes )
// example
$('<a>', {
    href: 'http://jquery.com'
});
// Of course you can write stupidly:
$( "<a href='http://jquery.com'></a>" );

 

(3) DOM loading

Usually JavaScript needs to be executed after the DOM is loaded, otherwise DOM manipulation may fail. jQuery provides a convenient method to listen for the completion of the DOM loading:

// method declaration
jQuery( callback )
// example
$(function(){
    // Execute after DOM is loaded
});

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326597755&siteId=291194637