二:Bringing pages to life
with jQuery
<img id="myImage" src="image.gif" alt="An image" class="someClass"
title="This is an image" data-custom ="some value"/>
1:As an example of using the each() method, we could use the following code to set the
id property of every element in the DOM to a name composed of the element’s tag
name and position within the DOM:
$('*').each(function(n){
this.id = this.tagName + n;
});
2:We can retrieve that attribute’s value, as if it were any of the standard
attributes
$("#myImage").attr("data-custom")
3:We can set that attribute’s value
$('*').attr('title',function(index,previousValue) {
return previousValue + ' I am element ' + index +
' and my name is ' + (this.id || 'unset');
});
another way:
$('input').attr(
{ value: '', title: 'Please enter a value' }
);
4:FORCING LINKS TO OPEN IN A NEW WINDOW
$("a[href^='http://']").attr("target","_blank");
5:SOLVING THE DREADED DOUBLE-SUBMIT PROBLEM
For the client side of the solution (the server-side code should still be written in a
paranoid fashion), we’ll hook into the form’s submit event and disable the submit
button after its first press.
$("form").submit(function() {
$(":submit",this).attr("disabled", "disabled");
});
6:Adding and removing class names
addClass removeClass
toggleClass Adds the specified class name if it doesn’t exist on an element, or removes the name from
elements that already possess the class name. Note that each element is tested individually, so
some elements may have the class name added, and others may have it removed.
function swapThem() {
$('tr').toggleClass('striped');
}
$(function(){/
$("table tr:nth-child(even)").addClass("striped");
$("table").mouseover(swapThem).mouseout(swapThem);
});
7:Another commonly desired ability is to obtain the list of classes defined for a particular
element as an array instead of the cumbersome space-separated list. We could
try to achieve that by writing
$("p:first").attr("className").split(" ");
Recall that the attr() method will return undefined if the attribute in question
doesn’t exist, so this statement will throw an error if the <p> element doesn’t possess
any class names.
We could solve this by first checking for the attribute
$.fn.getClassNames = function() {
var name = this.attr("className");
if (name != null) {
return name.split(" ");
}
else {
return [];
}
};
8:expand the width of all elements
in the wrapped set by 20 pixels as follows:
$("div.expandable").css("width",function(index, currentWidth) {
return currentWidth + 20;
});
9:GETTING AND SETTING DIMENSIONS
$("div.myElements").width(500)
is identical to
$("div.myElements").css("width",500)
$(function(){
$(window).resize(displayDimensions);
displayDimensions();
});
function displayDimensions() {
$('#display').html(
$('#testSubject').width()+'x'+$('#testSubject').height()
);
10:html()
Obtains the HTML content of the first element in the matched set.
html(content)
Sets the passed HTML fragment as the content of all matched elements.
text()
Concatenates all text content of the wrapped elements and returns it as the result of the method.
text(content)
Sets the text content of all wrapped elements to the passed value. If the passed text contains
angle brackets (< and >) or the ampersand (&), these characters are replaced with their equivalent
HTML entities.
11:Appends the passed HTML fragment or elements to the content of all matched elements.
$('p').append('<b>some text<b>');
This statement moves all links with the class appendMe to the end of the child list of all
<p> elements with the class appendToMe. If there are multiple targets for the operation,
the original element is cloned as many times as is necessary and appended to the
children of each target. In all cases, the original is removed from its initial location.
$("p.appendToMe").append($("a.appendMe"))
Prepends the passed HTML fragment or elements to the content of all matched elements.
prepend(content)
Inserts the passed HTML fragment or elements into the DOM as a sibling of the target elements,
positioned before the targets. The target wrapped elements must already be part of the DOM.
before(content)
Inserts the passed HTML fragment or elements into the DOM as a sibling of the target elements
positioned after the targets. The target wrapped elements must already be part of the DOM.
after(content)
Adds all elements in the wrapped set to the end of the content of the specified target(s).
appendTo(targets)
Adds all elements in the wrapped set to the beginning of the content of the specified target(s).
prependTo(targets)
Adds all elements in the wrapped set to the DOM just prior to the specified target(s).
insertBefore(targets)
Adds all elements in the wrapped set to the DOM just after the specified target(s).
insertAfter (targets)
$('<p>Hi there!</p>').insertAfter('p img');
12:To wrap each link with the class surprise in a <div> with the class hello, we could
write
$("a.surprise").wrap("<div class='hello'></div>")
Wraps the elements of the matched set, as a unit, with the passed HTML tags or a clone of the
passed element.
wrapAll(wrapper)
13:Removes all elements in the wrapped set from the page DOM.
remove(selector)
Removes all elements in the wrapped set from the page DOM, retaining any bound events and
jQuery data.
detach(selector)
The detach() method is the preferred means of removing an element that we’ll want
to put back into the DOM at a later time with its events and data intact.
13:This statement makes copies of all image elements and appends them to all <fieldset>
elements with the class name photo.
$('img').clone().appendTo('fieldset.photo');
This statement performs the same operation as the previous example, but after the
insertion of the clones, the end() method is used to select the original wrapped set
(the original targets) and hide them.
$('ul').clone().insertBefore('#here').end().hide();
14:replace all images on the
page that have alt attributes with <span> elements that contain the alt values of the
images. Employing each() and replaceWith() we could do it like this:
$('img[alt]').each(function(){
$(this).replaceWith('<span>'+ $(this).attr('alt') +'</span>')
});
15:Returns the value attribute of the first element in the matched set. When the element is a multiselect
element, the returned value is an array of all selections.
Attention:This method also doesn’t distinguish between the
checked or unchecked states of checkboxes and radio buttons, and will simply return
the value of checkboxes or radio buttons as defined by their value attribute, regardless
of whether they’re checked or not.
val()
This expression returns the value of the single checked radio button (or undefined if
none is checked)
$('[name="radioGroup"]:checked').val()
var checkboxValues = $('[name="checkboxGroup"]:checked').map(
function(){ return $(this).val(); }
).toArray();
16:This statement will search all the <input> and <select> elements on the page for values
that match any of the input strings: one, two, or three. Any checkboxes or radio buttons
that are found to match will become checked, and any options that match will
become selected.
$('input,select').val(['one','two','three']);