1. Operation attributes
The above describes how to filter out the required elements. After getting the element, you need to operate on it. A common requirement is to iterate through the obtained set of elements and perform an operation on each element. The function provided by jQuery is
each(iterator), where iterator is a function that accepts an integer as a parameter, indicating the number of elements. Let's look at a simple example.
jQuery Operation Image Gallery
March 13th,2010
Check the results using Firebug:
In the above example, the native JavaScript method is used to access attributes. jQuery provides a more general method to access attributes, attr:
attr(name), if name is a string, get the value of name of the attribute of the first element; if name is an object, the attributes of the object are copied to all elements of the packaging set as attributes of the element .
attr(name,value), when name is a string, set the value of attribute name to value. When value is a function, call this function for each element in the packaging set to set it The value of name is set to the return value of the function.
Look at a simple example, the html code still uses the above:
$(function() {
$('body').children().attr('title', function(n) {
return"This is " n "th element";
});
$('img').attr('alt', 'A photo taken by YinZixin');
alert($ ('h1').attr('title'));
});
The result is:
To delete an attribute, use the removeAttr(name) method.
Please note that there is a special attribute class among the attributes. The class attribute is very commonly used, and it happens to be a keyword in JavaScript. To access the class attribute, use className instead of class. For example:
$('img').attr('className', 'photo'); class is different from other attributes. An element can have multiple classes, separated by spaces, for example class='big strong ', because class is special and commonly used, jQuery has a special method to handle class attributes.
addClass(names), add a class;
removeClass(names), delete a class;
toggleClass(names), if the element has the class, delete it, otherwise add it.
The names is a string, which can be composed of multiple class names separated by spaces. addClass and removeClass are easy to use without giving examples. toggleClass is particularly simple and practical. Let’s look at an example below. The html code still uses the above:
$(function() {
$('td:odd').append($('span'));
$('div:first').append($( 'p')).append('sub title');
});
1 | |
2 | |
table>
Hello JQuery
Title