JQuery 7 ways to build jQuery functions

  • 2020-03-30 03:07:54
  • OfStack

$(selectorStr[, restricted range]), accepts a selector (a string conforming to jQuery specification), returns a jQuery object;


 //$(selector[, restricted range])
         $(".guo").click(function () {//There's no context argument here
             $("a.aguo", this).css({"color":"red"});//This is the context parameter, which is used to limit the scope
         });

$(htmlStr[, document object]),$(HTML [,json object]) passes in the HTML string, creating a new dom element

When a string is passed in, the constructor determines whether it is a selector string or an HTML string.
If the selector string: then traverses the dom, looking for elements that match it. If there are no matched elements,
Returns an empty jQuery object; Otherwise the matching elements are created one to one jQuery object.


 //$(htmlStr[, document object])
         $("<div> Hello, everyone </div>").append("body"); //Simple tags: no tape nodes

$(dom element),$(dom element collection) converts dom elements into jQuery objects.

The jQuery constructor creates a dom node using js's original document.createelement () method


 $("<div><a> Hello, everyone </a></div>").append("body"); //Complex tag: contains child nodes.

Four :$(custom object) encapsulates the ordinary object as jQuery object.

JQuery will use the method of document fragment () to insert all the child nodes into the [document object] at once, which is a document if it is not specified here. [$(HTML, json object])  

When HTML is a simple tag, her second argument can be a json object that contains the attributes or events of the dom element.


 //[$(HTML, json object])
  $("<div></div>", {
             "class": "gys", //Because class is a js keyword, use quotes
             text: " Hello, everyone ",
             click: function () { alert(" Let me do "); }
         }).append("body");

Five :$(callback function) binds the ready event listener function to execute when the Dom is loaded.

$(element) or $(elements)

Pass in a dom object or a collection of dom objects


 ("div.guo").click(function () {
             $(this).slideUp();
         });

Take a jQuery object and return a copy of the jQuery object

$(object);

Pass in a normal object


 var obj = { name: "guo", age: 24 };
 var $obj = $(obj);
 $obj.on("guo", function () {
  alert(" A custom event is started ");
 });
 $obj.trigger("guo");

Seven :$() creates an empty jQuery object.

$(callback) passes in a function


 $(function () { })

This represents the execution of the function after the Dom is loaded.

$(the jQuery Object);

When a jQuery object is passed in, a copy of that jQuery object is created and returned, a copy of exactly the same Dom object referenced by the passed jQuery object.


Related articles: