Read Time:14 minsLanguages:url-selector#selectionChanged" data-controller="url-selector">EnglishDeutschEspañolBahasa IndonesiaPусскийукраїнська моваSo you"ve been playing with jQuery for a while now, you"re starting to get the hang of it, and you"re really liking it! Are you ready to take your jQuery knowledge to level two? Today, I"ll demonstrate twenty functions and features you probab" />
So you"ve been playing with jQuery for a while now, you"re starting to lớn get the hang of it, and you"re really liking it! Are you ready lớn take your jQuery knowledge to cấp độ two? Today, I"ll demonstrate twenty functions & features you probably haven"t seen before!
Sometimes you want lớn insert something into the DOM, but you don"t have any good hooks to bởi it with; append() or prepend() aren"t going khổng lồ cut it và you don"t want to địa chỉ cửa hàng an extra element or id. These two functions might be what you need. They allow you to lớn insert elements into the DOM just before or after another element, so the new element is a sibling of the older one.
$("#child").after($("")).text("This becomes a sibling of #child"));$("#child").before($("")).text("Same here, but this is go about #child"));You can also vày this if you"re working primarily with the element you want to lớn insert; just use the insertAfter() or insertBefore functions.
Bạn đang xem: 20 helpful jquery api documentation, jquery event methods
$("I"ll be a sibling of #child
").insertAfter($("#child"));The change() method is an sự kiện handler, just lượt thích click() or hover(). The change event is for textareas, text inputs, và select boxes, and it will fire when the value of the target element is changed; lưu ý that this is different from the focusOut() or blur() sự kiện handlers, which fire when the element loses focus, whether its value has changed or not.
The change() event is perfect for client-side validation; it"s much better than blur(), because you won"t be re-validating fields if the user doesn"t change the value.
$("input3 Context
Context is both a parameter and a property in jQuery. When collecting elements, you can pass in a second parameter khổng lồ the jQuery function. This parameter, the context, will usually be a DOM element, & it limits the elements returned to item matching your selector that are children of the context element. That might sound a bit confusing, so check out this example:
Hello World
var hi1 = $(".hello"), hi2 = $(".hello", $("#wrap").get(0));console.group("hi1");console.log("Number of elements in collection:", hi1.length);console.log("Context of the collection:", hi1.context);console.groupEnd();console.group("hi2");console.log("Number of elements in collection:", hi2.length);console.log("Context of the collection:", hi2.context);console.groupEnd();
$("ul#options li").click(function () $("a", this) . . .);
$("#wrap").data("myKey", "myValue");$("#container").data( myOtherKey : "myOtherValue", year : 2010 );To get your data back, just call the method with the key of value you want.
$("#container").data("myOtherKey"); //returns "myOtherValue"$("#container").data("year"); //returns 2010To get all the data that corresponds with an element, call data without any parameters; you"ll get an object with all the keys and values you"ve given khổng lồ that item.If you want lớn delete a key/value pair after you"ve added it to an element, just hotline removeData(), passing in the correct key.
$("#container").removeData("myOtherKey");
HTML
Start Animating Stop Animating showroom to Queue
JavaScript
$("#start").click(animateBox);$("#reset").click(function() $("div").queue("fx", <>););$("#add").click(function() $("div").queue( function() $(this).animate( height : "-=25", 2000); $(this).dequeue(); ););function animateBox() $("div").slideUp(2000) .slideDown(2000) .hide(2000) .show(2000, animateBox);So, here"s what"s going on: in the animateBox function, we"re setting up a queue of animations; notice that the last one calls back khổng lồ the function, so this will continually repeat the queue. When we click li#start, the function is called & the queue begins. When we click li#reset, the current animation finishes, and then the div stops animating. What we"ve done with jQuery is set the queue named "fx" (remember, the default queue) to lớn an empty array; essentially, we"ve emptied the queue. And what about when we click li#add? First, we"re calling the queue function on the div; this adds the function we pass into it to lớn the over of the queue; since we didn"t specify a queue as the first parameter, "fx" is used. In that function, we animate the div, and then gọi dequeue() on the div, which removes this function from the queue và continues the queue; the queue will continue repeating, but this function will not be part of it.
When you"re queuing up a chain of animations, you can use the delay() method lớn pause the animation for a length of time; pass that time as a parameter in milliseconds.
$("div").hide().delay(2000).show(); // div will stay hidden for 2 seconds before showing.
$("#el").click(function () /*******/ );. . . You"re really just using a wrapper for the bind() method? to lớn use the bind() method itself, you can pass the sự kiện type as the first parameter và then the function as the second.
If you use a lot of events, you can categorize them with namespacing; just showroom a period after the event name and địa chỉ your namespace.
$("#el").bind("click", function () /*******/ );$("#el").bind("click.toolbarEvents", function () /*******/ ); // namespacedYou can also assign the same function to multiple events at the same time, by separating them with spaces. So if you wanted to lớn make a hover effect, you could start this way:
$("#el").bind("mouseover mouseout", function () /*******/ );You can also pass data to the function if you"d like, by adding a third parameter (in the second position).
$("#el").bind("click", status : "user-ready" , function () switch(event.data.status) /********/ );Sooner or later, you"ll find yourself inserting element into the DOM via an sự kiện handler; however, you"ll find that the sự kiện handlers you"ve made with bind (or its wrappers) don"t work for inserted elements. In cases lượt thích this, you"ll need to lớn use the live() (or delegate) method; this will địa chỉ cửa hàng the event handlers to lớn the appropriate inserted elements.
Xem thêm: Crm Là Gì? Phần Mềm Crm Là Gì ? Customer Relationship Management Là Gì
$(".toggle").live(function () /* obatambeienwasirherbal.com */ $("Enable Beta Features").appendTo($("#optionsPanel")); /* more obatambeienwasirherbal.com */);To remove event handlers created with bind(), use the unbind() method. If you don"t pass it any parameters, it will remove all the handlers; you can pass in the event type to lớn only remove sự kiện handlers of that type; to lớn remove events from a specific namespace, add the namespace, or use it alone. If you just want to remove a certain function, pass its name along as the second parameter.
$("button").unbind(); // removes all$("button").unbind("click"); // removes all clicks$("button").unbind(".toolbarEvents"); // removes all events from the toolbarEvents namespace$("button").unbind("click.toolbarEvents"); // removes all clicks from the toolbarEvents namespace$("button").unbind("click", myFunction); // removes that one handlerNote that you can bind/unbind functions you"ve passed in anonymously; this only works with the functions name.If you"re trying to lớn unbind an sự kiện from inside the function called by the event, just pass unbind() the sự kiện object.
$("p").bind("click", function (event) $("p").unbind(event); );You can"t use unbind() for live events; instead, use the die(). Without parameters, it will remove all live events from the element collection; you can also pass it just the sự kiện type, of the sự kiện type & the function.
$("span").die(); // removes all$("span").die("mouseover"); // removes all mouseovers$("span").die("mouseover", fn); // remove that one handlerAnd now, you can wield jQuery events with deftness và power!
You should also review the delegate() method, as there can be substantial performance benefits to lớn using it over live().
If you"re looking for a specific element within a mix of elements, you can pass the index of the element to the eq() method and get a single jQuery element. Pass in a negative index lớn count back from the end of the set.
var ps = $("p");console.log(ps.length); // logs 3;ps.eq(1).addClass("emphasis"); // just adds the class khổng lồ the second công trình (index in zero-based)You can also use :eq() in your selectors; so the previous example could have been done like this:
$("p:eq(1)").addClass("emphasis");
You can specify an index to get only one element.
alert( $("p") ); //
Jeffrey Way did a great quick tip about the $.grep not long ago; kiểm tra that out to lớn see how to lớn use it!
var nums = "1,2,3,4,5,6,7,8,9,10".split(",");nums = $.grep(nums, function(num, index) // num = the current value for the thành tựu in the array // index = the index of the tác phẩm in the array return num > 5; // returns a boolean);console.log(nums) // 6,7,8,9,10
$(":animated"); // returns all elements currently animating$(":contains(me)"); // returns all elements with the text "me"$(":empty"); // returns all elements with no child nodes or text$(":parent"); // returns all elements with child nodes or text$("li:even"); // returns all even-index elements (in this case, s)$("li:odd"); // can you guess?$(":header"); // returns all h1 - h6s.$("li:gt(4)"); // returns all elements with an (zero-based) index greater than the given number$("li:lt(4)"); // returns all element with an index less than the given number$(":only-child"); // returns all . . . Well, it should be obviousThere are more, of course, but these are the quality ones.
Sometimes you want khổng lồ make sure the parameter that was passed to lớn a function was the corrent type; these functions make it easy khổng lồ do. The first three are pretty self explanatory:
$.isArray(<1, 2, 3>); // returns true$.isEmptyObject(); // returns true$.isFunction(function () /****/ ); // returns trueThe next one isn"t as obvious; isPlainObject() will return true if the parameter passed in was created as an object literal, or with new Object().
function Person(name) this.name = namereturn this;$.isPlainObject()); // returns true$.isPlainObject(new Object()); // returns true$.isPlainObject(new Person()); // returns false
var ps = $("p");$.isArray(ps); //returns false;ps = $.makeArray(ps);$.isArray(ps); // returns true;
$("ul#nav li a").map(function() return $(this).attr("title");); // now the collection is the links titles// this could be the beginning of a tooltip plugin.
$.post("somePage.php", function (data) /*****/data = $.parseJSON(data); /*****/);
var person = name : "Andrew", meet : function () alert("Hi! My name is " + this.name); ;person.meet();$("#test").click(person.meet);By itself, person.meet() will alert correctly; but when it"s called by the sự kiện handler, it will alert "Hi! My name is undefined." This is because the function is not being called in the right context. To lớn fix this, we can use the proxy() function:
$("#test").click($.proxy(person.meet, person));// we could also do $.proxy(person, "meet")The first parameter of the proxy function is the method to lớn run; the second is the context we should run it in. Alternatively, we can pass the context first, and the method name as a string second. Now you"ll find that the function alerts correctly.
Prefer a clip quick tip on $.proxy?
If you"d lượt thích to replace DOM elements with other ones, here"s how to bởi vì it. We can hotline replaceAll() on elements we"ve collected or created, passing in a selector for the elements we"d lượt thích to replace. In this example, all elements with the error class will be replaced with the span we"ve created.
$("The error has been corrected").replaceAll(".error");The replaceWith() method just reverses the selectors; find the ones you want to lớn replace first:
$(".error").replaceWith("The error has been corrected");You can also pass these two methods functions that will return elements or HTML strings.
The serialize() method is what lớn use for encoding the values in a size into a string.
HTML
JavaScript
console.log($("form").serialize()); // logs : name=John+Doe&url=http%3A%2F%2Fwww.example.comYou can use serializeArray() to lớn turn the khung values into an array of objects instead of a string:
console.log($("form").serializeArray()); // logs : < name : "name", value : "John Doe" , name : "url", value : "http://www.example.com" >