SoFunction
Updated on 2025-04-13

jQuery Absolute Introduction Page 2/2


In the click event, we use $(this).next() to find a dd element immediately below dt, which allows us to quickly select the answer below the clicked question
slideUp(speed,[callback]) speed slow normal fast or numeric value, callback function
All matching elements are dynamically hidden by height change (downgrading up), optionally triggering a callback function after hiding is complete.
This animation effect only adjusts the height of the element, so that the matching elements can be hidden in a "sliding" way.
slideDown(speed,[callback])
All matching elements are displayed dynamically by changing height (increasing down), and an optional callback function is triggered after the display is completed.
This animation effect only adjusts the height of the element, so that the matching elements can be displayed in a "sliding" manner.
In addition to selecting elements of the same level, you can also select elements of the parent level. Maybe you want to display the parent element of the article when the user moves the mouse to a link in a certain paragraph of the article, which is the highlight of the article. Try this:
Copy the codeThe code is as follows:

$(document).ready(function() {
$("a").hover(function() {
$(this).parents("p").addClass("highlight");
}, function() {
$(this).parents("p").removeClass("highlight");
});
});
$(document).ready(callback) abbreviation: $(function)
$(function() {
// code to execute when the DOM is ready
});

Apply to our Hello world example, you can do this:
Copy the codeThe code is as follows:

$(function() {
$("a").click(function() {
alert("Hello world!");
});
});

Although these examples can also be implemented without using AJAX, it is not shown that we will do that. We use jQuery to generate a DIV container with the ID "rating".
Copy the codeThe code is as follows:

$(document).ready(function() {
// generate markup
var ratingMarkup = ["Please rate: "];
for(var i=1; i <= 5; i++) {
ratingMarkup[] = "<a href='#'>" + i + "</a> ";
}
// add markup to container and applier click handlers to anchors
$("#rating").append( ('') ).find("a").click(function(e) {
();
// send requests
$.post("", {rating: $(this).html()}, function(xml) {
// format result
var result = [
"Thanks for rating, current average: ",
$("average", xml).text(),
", number of votes: ",
$("count", xml).text()
];
// output result
$("#rating").html((''));
} );
});
});

This code generates 5 links and appends them to the container id "rating". When one of the links is clicked, the score indicated by the link will be sent in the form of rating parameters. The result will then be passed back from the server side in XML and added to the container to replace these links.
A common problem when loading content using AJAX is: when loading an event handle to an HTML document, you also need to apply these events on the loading content. You have to apply these event handles after the content is loaded. In order to prevent repeated execution of the code, you may use the following function:
Copy the codeThe code is as follows:

// lets use the shortcut
$(function() {
var addClickHandlers = function() {
$("").click(function() {
$("#target").load(, addClickHandlers);
});
};
addClickHandlers();
});

Now addClickHandlers is executed only once after the DOM loading is completed, which is after each time the user clicks a link with clickMeToLoadContent and the content is loading.
Please note that the addClickHandlers function is defined as a local variable, not a global variable (such as function addClickHandlers() {...}). This is done to prevent conflicts with other global variables or functions.
Another common question is about the parameters of the callback. You can specify the callback method with an extra parameter. The simple method is to include this callback method in a different function:
// get some data
var foobar = ...;
// specify handler, it needs data as a paramter
var handler = function(data) {
...
};
// add click handler and pass foobar!
$('a').click( function(event) { handler(foobar); } );
// if you need the context of the original handler, use apply:
$('a').click( function(event) { (this, [foobar]); } );
Animate me (to make me liven): Use FX
Some dynamic effects can be expressed using show() and hide():
Copy the codeThe code is as follows:

$(document).ready(function() {
$("a").toggle(function() {
$(".stuff").hide('slow');
}, function() {
$(".stuff").show('fast');
});
});

You can combine it with animate() to create some effects, such as a sliding effect with a gradient:
Copy the codeThe code is as follows:

$(document).ready(function() {
$("a").toggle(function() {
$(".stuff").animate({
height: 'hide',
opacity: 'hide'
}, 'slow');
}, function() {
$(".stuff").animate({
height: 'show',
opacity: 'show'
}, 'slow');
});
});
toggle(fn,fn)

After each click, the function is called in turn.
If a matching element is clicked, the specified first function is triggered, when the same element is clicked again, the specified second function is triggered, and if there are more functions, it is triggered again, until the last one. Each subsequent click repeats the sequence of calls to these functions.
You can use unbind("click") to delete.
animate(params,options)
Functions used to create custom animations.
The key to this function is to specify the animation form and result style attribute objects. Each property in this object represents a style property that can be varied (such as "height", "top", or "opacity").
Note: All specified attributes must be in camel form, such as marginLeft instead of margin-left.
The value of each attribute indicates how much of this style attribute reaches when the animation ends. If it is a numeric value, the style attribute will gradually change from the current value to the specified value. If you are using string values ​​such as "hide", "show", or "toggle", the default animation form will be called for this property.
Copy the codeThe code is as follows:

$("#go1").click(function(){
$("#block1").animate( { width: "90%"}, { queue: false, duration: 5000 } )
.animate( { fontSize: '10em' } , 1000 )
.animate( { borderWidth: 5 }, 1000);
});
$("#go2").click(function(){
$("#block2").animate( { width: "90%"}, 1000 )
.animate( { fontSize: '10em' } , 1000 )
.animate( { borderWidth: 5 }, 1000);
});

Using the tablesorter plugin (table sorting)
This table sorting plug-in allows us to sort by a certain column on the client side, introduce jQuery and the js files of this plug-in, and then tell the plug-in which table you want to have sorting function.
To test this example, first add the code like the following line:
<script src="lib/" type="text/javascript"></script>
Then you can call it like this:
$(document).ready(function() {
$("#large").tableSorter();
});
Now click on the head area of ​​the first row of the table, and you can see the sorting effect. Click again and arrange it in the reverse order.
This table can also add some highlighting effects, we can do such an interlaced background color (zebra crossing) effect:
Copy the codeThe code is as follows:

$(document).ready(function() {
$("#large").tableSorter({
stripingRowClass: ['odd','even'], // Class names for striping supplyed as a array.
stripRowsOnStartUp: true // Strip rows on tableSorter init.
});
});

Make your own plug-in
It is very easy to write your own jQuery plugin. If you follow the following principles, it can also be easily used by others.
1. Give your plugin a name, in this example we call it "foobar".
2. Create a file like this: jquery.[yourpluginname].js, for example, we create a
3. Create one or more plug-in methods, using the method of inheriting jQuery objects, such as:
4. = function() {
5. // do something
6. }
7. Optional: Create a function for help description, such as:
8. = {
9. height: 5,
10. calculateBar = function() { ... },
11. checkDependencies = function() { ... }
12. }
You can now use these helper functions in your plugin:
= function() {
// do something
(value);
// do something else
};
(object)
Extend the jQuery element set to provide new methods (usually used to make plugins).
({
check: function() {
return (function() { = true; });
},
uncheck: function() {
return (function() { = false; });
}
});
result:
$("input[type=checkbox]").check();
$("input[type=radio]").uncheck();
13. Optional l: Create a default initial parameter configuration, which can also be set by the user, such as:
14. = function(options) {
15. var settings = {
16. value: 5,
17. name: "pete",
18. bar: 655
19. };
20. if(options) {
21. (settings, options);
22. }
23. }
(target,obj1,[objN])
Extend an object with one or more other objects, returning the extended object.
Used to simplify inheritance.
var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
(settings, options);
result:
settings == { validate: true, limit: 5, name: "bar" }
Now you can use the plug-in without any configuration, and the default parameters take effect at this time:
$("...").foobar();
Or add these parameter definitions:
$("...").foobar({
value: 123,
bar: 9
});
If you release your plugin, you should also provide some examples and documentation, and most plugins have these good reference documentation.
Now you should have the foundation for writing a plugin, let's try to use this knowledge to write your own plugin.
Many people try to control whether all radio or checkboxes are selected, such as:
$("input[type='checkbox']").each(function() {
= true;
// or, to uncheck
= false;
// or, to toggle
= !;
});
Note: In jQuery 1.2 and above, selecting all checkboxes should use input:checkbox, so the first line of the above code can be written as:
$('input:checkbox').each(function() {
Whenever each of your code appears, you should rewrite the above code to construct a plugin, very directly:
$. = function() {
return (function() {
= true;
});
};
This plugin can now be used like this:
$('input:checkbox').check();
Note: In jQuery1.2 and above, selecting all checkboxes should use input:checkbox. The original text is: $("input[type='checkbox']").check();
Now you should also be able to write uncheck() and toggleCheck(). But stop for a while and let our plugin receive some parameters.
$. = function(mode) {
var mode = mode || 'on'; // if mode is undefined, use 'on' as default
return (function() {
switch(mode) {
case 'on':
= true;
break;
case 'off':
= false;
break;
case 'toggle':
= !;
break;
}
});
};
Here we set the default parameters, so it is OK to omit the "on" parameter. Of course, you can also add "on", "off", or "toggle", such as:
$("input[type='checkbox']").check();
$("input[type='checkbox']").check('on');
$("input[type='checkbox']").check('off');
$("input[type='checkbox']").check('toggle');
If there are more than one parameter setting, it will be a little complicated. If you want to set only the second parameter when using it, you need to write null at the first parameter position.
From the usage of the tablesorter plugin in the previous chapter, we can see that all parameters can be omitted to use or reset each parameter through a key/value pair.
As an exercise, you can try to rewrite the functionality implemented in the example above as a plugin. The skeleton of this plugin should be like this:
$. = function(options) {
var container = this; // instead of selecting a static container with $("#rating"), we now use the jQuery context
var settings = {
url: ""
// put more defaults here
// remember to put a comma (",") after each pair, but not after the last one!
};
if(options) { // check if options are present before extending the settings
$.extend(settings, options);
}
// ...
// rest of the code
// ...
return this; // if possible, return "this" to not break the chain
});
Previous page12Read the full text