Vous êtes sur la page 1sur 8

Selectores de JQuery

Syntax
$("*")
$(this)
$("p.intro")
$("p:first")
$("ul li:first")
$("ul li:first-child")
$("[href]")
$("a[target='_blank']")
value equal to "_blank"
$("a[target!='_blank']")
value NOT equal to "_blank"
$(":button")
ts of type="button"
$("tr:even")
$("tr:odd")
Eventos
Mouse Events
/Window Events
click
dblclick
mouseenter
mouseleave
mousedown
mouseup
hover
on

Selects
Selects
Selects
Selects
Selects
Selects
Selects
Selects

Description
all elements
the current HTML element
all <p> elements with class="intro"
the first <p> element Try it
the first <li> element of the first <ul>
the first <li> element of every <ul>
all elements with an href attribute
all <a> elements with a target attribute

Selects all <a> elements with a target attribute


Selects all <button> elements and <input> elemen
Selects all even <tr> elements
Selects all odd <tr> elements

Keyboard Events

Form Events

Document

keypress
keydown
keyup

submit
change
focus
blur

load
resize
scroll
unload
ready

sintaxis para los metodos


$("p").click();
$("p").click(function(){
// action goes here!!
});
El mtodo $(document).ready() nos permite ejecutar una funcin cuando el documento s
e ha cargado completamente.
.hover() realiza dos funciones y es una combinacin de los MouseEnter() y mouselea
ve().
.on() concede uno o ms controladores de eventos para los elementos seleccionados.
$("p").on({
mouseenter: function(){
$(this).css("background-color", "lightgray");
},
mouseleave: function(){
$(this).css("background-color", "lightblue");
},
click: function(){
$(this).css("background-color", "yellow");
}
});
Efectos
$(selector).hide(speed,callback);
$(selector).show(speed,callback);
$(selector).toggle(speed,callback);

El parmetro de velocidad opcional especifica la velocidad de ocultar / mostrar, y


puede tomar los siguientes valores: "lento", "rpido", o en milisegundos.
Metodos de funfido
$(selector).fadeIn(speed,callback);
en un elemento oculto.
$(selector).fadeOut(speed,callback);
un elemento visible
$(selector).fadeToggle(speed,callback);
() y fadeOut mtodos ().
$(selector).fadeTo(speed,opacity,callback):
una opacidad dada (valor entre 0 y 1).
Metodos de deslizamientos
$(selector).slideDown(speed,callback);
se por un elemento.
$(selector).slideUp(speed,callback);
se hacia arriba un elemento.
$(selector).slideToggle(speed,callback);
wn () y slideUp mtodos ().
Animaciones
$(selector).animate({params},speed,callback);
imaciones personalizadas.
$(selector).stop(stopAll,goToEnd);
una animacin o efecto antes de que termine.

se utiliza a desaparecer
se utiliza a desaparecer
alterna entre la fadeIn
permite la decoloracin a

se utiliza para deslizar


se utiliza para deslizar
alterna entre la slideDo

se utiliza para crear an


se utiliza para detener

Tenga en cuenta que mltiples propiedades pueden ser animados al mismo tiempo.
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
Tambin es posible definir valores relativos (el valor es entonces en relacin con e
l valor actual del elemento). Esto se hace poniendo + = o - = delante del valor.
Incluso puede especificar el valor de una propiedad de animacin como "espectculo",
"ocultar" o "cambiar":
$("button").click(function(){
$("div").animate({
height: 'toggle'
});
});
As que, si quieres realizar diferentes animaciones, uno tras otro, tomamos ventaj
a de la funcionalidad de cola
$("button").click(function(){
var div = $("div");
div.animate({left: '100px'}, "slow");
div.animate({fontSize: '3em'}, "slow");
});
Tres mtodos simples, pero tiles, jQuery para la manipulacin DOM son:
text() - Establece o devuelve el contenido del texto de los elementos selecciona
dos
html() - Establece o devuelve el contenido de los elementos seleccionados (inclu

yendo cdigo HTML)


val() - Establece o devuelve el valor de los campos del formulario
attr() - se utiliza para obtener valores de atributos.
utilizamos los mismos tres mtodos de la pgina anterior para establecer el contenid
o:
estos cuatro mtodos de jQuery que se utilizan para aadir nuevos contenidos:
append () - contenido de insertos en el extremo de los elementos seleccionados
prepend () - Inserciones contenido al principio de los elementos seleccionados
after() - Inserta el contenido despus de que los elementos seleccionados
before() - contenido insertos antes de que los elementos seleccionados
Para eliminar elementos y contenidos, hay principalmente dos mtodos de jQuery:
remove () - Elimina el elemento seleccionado (y sus elementos secundarios)
empty () - Elimina los elementos secundarios del elemento seleccionado
hay varios mtodos para la manipulacin de CSS. Veremos los siguientes mtodos:
addClass () - Aade una o ms clases a los elementos seleccionados
removeClass () - Elimina una o ms clases de los elementos seleccionados
toggleClass () - Cambia entre la adicin / eliminacin de clases de los elementos se
leccionados
css () - Establece o devuelve el atributo de estilo
Para devolver el valor de una propiedad CSS especificado, utilice la siguiente s
intaxis:
css("propertyname");
Para establecer una propiedad CSS especificado, utilice la siguiente sintaxis:
css("propertyname","value");
Para configurar mltiples propiedades CSS, utilice la siguiente sintaxis:
css({"propertyname":"value","propertyname":"value",...});
Dimensiones
jQuery tiene varios mtodos importantes para trabajar con dimensiones:
width () - establece el mtodo o devuelve el ancho de un elemento (no incluye rell
eno, borde y margen).
height() - stablece el mtodo o devuelve la altura de un elemento (no incluye rell
eno, borde y margen).
innerWidth () - devuelve el ancho de un elemento (incluye relleno).
innerHeight () - devuelve la altura de un elemento (incluye relleno).
outerWidth () - devuelve el ancho de un elemento (incluye el relleno y el borde)
.
outerHeight () - devuelve la altura de un elemento (incluye el relleno y el bord
e).
Metodos GET y POST
$.get(URL,callback); - solicita datos del servidor con una peticin HTTP GET.
$.post(URL,data,callback); - solicita datos del servidor mediante una solicitud
HTTP POST.
Metodos de eventos
Method / Property
Description
bind()
Attaches event handlers to elements
blur()
Attaches/Triggers the blur event
change()
Attaches/Triggers the change event
click()
Attaches/Triggers the click event
dblclick()
Attaches/Triggers the double click event
delegate()
Attaches a handler to current, or future
, specified child elements of the matching elements
die()
Removed in version 1.9. Removes all even
t handlers added with the live() method
error()
Deprecated in version 1.8. Attaches/Trig

gers the error event


event.currentTarget
The current DOM element within the event
bubbling phase
event.data
Contains the optional data passed to an
event method when the current executing handler is bound
event.delegateTarget
Returns the element where the currentlycalled jQuery event handler was attached
event.isDefaultPrevented()
Returns whether event.preventDefault() w
as called for the event object
event.isImmediatePropagationStopped() Returns whether event.stopImmediatePropa
gation() was called for the event object
event.isPropagationStopped()
Returns whether event.stopPropagation()
was called for the event object
event.namespace
Returns the namespace specified when the
event was triggered
event.pageX
Returns the mouse position relative to t
he left edge of the document
event.pageY
Returns the mouse position relative to t
he top edge of the document
event.preventDefault()
Prevents the default action of the event
event.relatedTarget
Returns which element being entered or e
xited on mouse movement.
event.result
Contains the last/previous value returne
d by an event handler triggered by the specified event
event.stopImmediatePropagation()
Prevents other event handlers from being
called
event.stopPropagation()
Prevents the event from bubbling up the
DOM tree, preventing any parent handlers from being notified of the event
event.target
Returns which DOM element triggered the
event
event.timeStamp
Returns the number of milliseconds since
January 1, 1970, when the event is triggered
event.type
Returns which event type was triggered
event.which
Returns which keyboard key or mouse butt
on was pressed for the event
focus()
Attaches/Triggers the focus event
focusin()
Attaches an event handler to the focusin
event
focusout()
Attaches an event handler to the focusou
t event
hover()
Attaches two event handlers to the hover
event
keydown()
Attaches/Triggers the keydown event
keypress()
Attaches/Triggers the keypress event
keyup()
Attaches/Triggers the keyup event
live()
Removed in version 1.9. Adds one or more
event handlers to current, or future, selected elements
load()
Deprecated in version 1.8. Attaches an e
vent handler to the load event
mousedown()
Attaches/Triggers the mousedown event
mouseenter()
Attaches/Triggers the mouseenter event
mouseleave()
Attaches/Triggers the mouseleave event
mousemove()
Attaches/Triggers the mousemove event
mouseout()
Attaches/Triggers the mouseout event
mouseover()
Attaches/Triggers the mouseover event
mouseup()
Attaches/Triggers the mouseup event
off()
Removes event handlers attached with the
on() method
on()
Attaches event handlers to elements
one()
Adds one or more event handlers to selec

ted elements. This handler can only be triggered once per element
$.proxy()
Takes an existing function and returns a
new one with a particular context
ready()
Specifies a function to execute when the
DOM is fully loaded
resize()
Attaches/Triggers the resize event
scroll()
Attaches/Triggers the scroll event
select()
Attaches/Triggers the select event
submit()
Attaches/Triggers the submit event
toggle()
Removed in version 1.9. Attaches two or
more functions to toggle between for the click event
trigger()
Triggers all events bound to the selecte
d elements
triggerHandler()
Triggers all functions bound to a specif
ied event for the selected elements
unbind()
Removes an added event handler from sele
cted elements
undelegate()
Removes an event handler to selected ele
ments, now or in the future
unload()
Deprecated in version 1.8. Attaches an e
vent handler to the unload event
Metodos de efecto
Method
animate()
clearQueue()
selected elements
delay()
ected elements
dequeue()
en executes the function
fadeIn()
fadeOut()
fadeTo()
acity
fadeToggle()
ds
finish()
ns for the selected elements
hide()
queue()
nts
show()
slideDown()
slideToggle()
thods
slideUp()
stop()
lected elements
toggle()
metodos css y html
Method
addClass()
s
after()
append()
appendTo()
ments
attr()

Description
Runs a custom animation on the selected elements
Removes all remaining queued functions from the
Sets a delay for all queued functions on the sel
Removes the next function from the queue, and th
Fades in the selected elements
Fades out the selected elements
Fades in/out the selected elements to a given op
Toggles between the fadeIn() and fadeOut() metho
Stops, removes and completes all queued animatio
Hides the selected elements
Shows the queued functions on the selected eleme
Shows the selected elements
Slides-down (shows) the selected elements
Toggles between the slideUp() and slideDown() me
Slides-up (hides) the selected elements
Stops the currently running animation for the se
Toggles between the hide() and show() methods
Description
Adds one or more class names to selected element
Inserts content after selected elements
Inserts content at the end of selected elements
Inserts HTML elements at the end of selected ele
Sets or returns attributes/values of selected el

ements
before()
Inserts content before selected elements
clone()
Makes a copy of selected elements
css()
Sets or returns one or more style properties for
selected elements
detach()
Removes selected elements (keeps data and events
)
empty()
Removes all child nodes and content from selecte
d elements
hasClass()
Checks if any of the selected elements have a sp
ecified class name
height()
Sets or returns the height of selected elements
html()
Sets or returns the content of selected elements
innerHeight()
Returns the height of an element (includes paddi
ng, but not border)
innerWidth()
Returns the width of an element (includes paddin
g, but not border)
insertAfter()
Inserts HTML elements after selected elements
insertBefore()
Inserts HTML elements before selected elements
offset()
Sets or returns the offset coordinates for selec
ted elements (relative to the document)
offsetParent()
Returns the first positioned parent element
outerHeight()
Returns the height of an element (includes paddi
ng and border)
outerWidth()
Returns the width of an element (includes paddin
g and border)
position()
Returns the position (relative to the parent ele
ment) of an element
prepend()
Inserts content at the beginning of selected ele
ments
prependTo()
Inserts HTML elements at the beginning of select
ed elements
prop()
Sets or returns properties/values of selected el
ements
remove()
Removes the selected elements (including data an
d events)
removeAttr()
Removes one or more attributes from selected ele
ments
removeClass()
Removes one or more classes from selected elemen
ts
removeProp()
Removes a property set by the prop() method
replaceAll()
Replaces selected elements with new HTML element
s
replaceWith()
Replaces selected elements with new content
scrollLeft()
Sets or returns the horizontal scrollbar positio
n of selected elements
scrollTop()
Sets or returns the vertical scrollbar position
of selected elements
text()
Sets or returns the text content of selected ele
ments
toggleClass()
Toggles between adding/removing one or more clas
ses from selected elements
unwrap()
Removes the parent element of the selected eleme
nts
val()
Sets or returns the value attribute of the selec
ted elements (for form elements)
width()
Sets or returns the width of selected elements
wrap()
Wraps HTML element(s) around each selected eleme
nt
wrapAll()
Wraps HTML element(s) around all selected elemen

ts
wrapInner()
selected element

Wraps HTML element(s) around the content of each

Metodos de desplazamiento
Method
Description
add()
Adds elements to the set of matched elements
addBack()
Adds the previous set of elements to the current
set
andSelf()
Deprecated in version 1.8. An alias for addBack(
)
children()
Returns all direct children of the selected elem
ent
closest()
Returns the first ancestor of the selected eleme
nt
contents()
Returns all direct children of the selected elem
ent (including text and comment nodes)
each()
Executes a function for each matched element
end()
Ends the most recent filtering operation in the
current chain, and return the set of matched elements to its previous state
eq()
Returns an element with a specific index number
of the selected elements
filter()
Reduce the set of matched elements to those that
match the selector or pass the function's test
find()
Returns descendant elements of the selected elem
ent
first()
Returns the first element of the selected elemen
ts
has()
Returns all elements that have one or more eleme
nts inside of them
is()
Checks the set of matched elements against a sel
ector/element/jQuery object, and return true if at least one of these elements m
atches the given arguments
last()
Returns the last element of the selected element
s
map()
Passes each element in the matched set through a
function, producing a new jQuery object containing the return values
next()
Returns the next sibling element of the selected
element
nextAll()
Returns all next sibling elements of the selecte
d element
nextUntil()
Returns all next sibling elements between two gi
ven arguments
not()
Remove elements from the set of matched elements
offsetParent()
Returns the first positioned parent element
parent()
Returns the direct parent element of the selecte
d element
parents()
Returns all ancestor elements of the selected el
ement
parentsUntil()
Returns all ancestor elements between two given
arguments
prev()
Returns the previous sibling element of the sele
cted element
prevAll()
Returns all previous sibling elements of the sel
ected element
prevUntil()
Returns all previous sibling elements between tw
o given arguments
siblings()
Returns all sibling elements of the selected ele
ment
slice()
Reduces the set of matched elements to a subset

specified by a range of indices

Vous aimerez peut-être aussi