The usage of jquery simple selector. The most basic thing in jquery. 1. Use class and id to select HTML elements
Select the element whose id is "myDivId". Because the id is unique, always select one or zero elements.
The Code is as follows:
$ ('# MyDivId ')
Select "myCssClass" as the class. You can select any element whose class is "myCssClass.
The Code is as follows:
$ ('. MyCssClass ')
Obtains or sets the value of an element.
The Code is as follows:
Var myValue = $ ('# mydivid'). val (); // get the value of an element
$ ('# MyDivId'). val ("hello world"); // set the value of an element
When there is a. And: in the selected id, the first two backslashes are added.
The Code is as follows:
// Does not work
$ ("# Some: id ")
// Works!
$ ("# Some \: id ")
// Does not work
$ ("# Some. id ")
// Works!
$ ("# Some \. id ")
Or use the following
The Code is as follows:
Function jq (myid ){
Return '#' + myid. replace (/(: | \.)/g, '\ $1 ');
}
$ (Jq ('some. id '))
2. Test Elements
Use the is () method to test whether a class exists.
The Code is as follows:
If ($ ('# myDiv'). is ('. pretty '))
$ ('# MyDiv'). show ();
Test whether to hide
The Code is as follows:
If ($ ('# myDiv'). is (': Den den '))
$ ('# MyDiv'). show ();
After version 1.2, you can use the hasClass method for processing.
The Code is as follows:
$ ("P"). click (function (){
If ($ (this). hasClass ("protected "))
$ (This)
. Animate ({left:-10 })
. Animate ({left: 10 })
. Animate ({left:-10 })
. Animate ({left: 10 })
. Animate ({left: 0 });
});
Test whether the element exists
The Code is as follows:
If ($ ('# myDiv'). length)
$ ('# MyDiv'). show ();
3. Element disabling and permitting
The Code is as follows:
// Disable # x
$ ("# X"). attr ("disabled", "disabled ");
// Enable # x
$ ("# X"). removeAttr ("disabled ");
Code:
The Code is as follows:
One Two
// This doesn't work
$(this).find('li a').eq(2).text().replace('foo','bar');
// This works
var $thirdLink = $(this).find('li a').eq(2);
var linkText = $thirdLink.text().replace('foo','bar');
$thirdLink.text(linkText);
4. Checkbox selection/Cancellation
The Code is as follows:
// Check # x
$ ("# C"). attr ("checked", "checked ");
// Uncheck # x
$ ("# C"). removeAttr ("checked ");
Code:
The Code is as follows:
I'll be checked/unchecked.
5. Obtain the value and text of Select Opion.
The Code is as follows:
$ ("Select # myselect"). val ();
$ ("# Myselect option: selected"). text ();
Code:
The Code is as follows:
Mr Mrs MS Dr Prof
Replace the text of 3rd projects in 10 projects
The Code is as follows:
// This doesn' t work
$ (This). find ('Li A'). eq (2). text (). replace ('foo', 'bar ');
// This works
Var $ thirdLink = $ (this). find ('Li A'). eq (2 );
Var linkText = $ thirdLink. text (). replace ('foo', 'bar ');
$ ThirdLink. text (linkText );