domingo, 20 de mayo de 2012

La función attr de jquery




La función attr de jquery

attr() nos permite cambiar el valor de los atributos de los tags html, por ejemplo si quisieramos cambiar el atributo src de una imagen con jquery lo haríamos de la siguiente manera...

$("img").attr("src", "imagen.jpg");

de esta sencilla manera podremos cambiar cuantos atributos sean necesarios.

En el siguiente ejemplo cambiaremos el valor del atributo width y height de una etiqueta <img> al hacer click sobre un botón, definiremos un valor diferente al que contiene actualmente.



El código del ejemplo es el siguiente...

<!-- By http://jquery-manual.blogspot.com -->
<!DOCTYPE HTML>
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.2.min.js'></script>
<script type="text/javascript">
$(document).ready(function() {
$(":button#boton").click(function(){
$("img#imagen").attr("width", "360");
$("img#imagen").attr("height", "360");
});
});
</script>
</head>
<body>
<input type="button" id="boton" value="Cambiar valor del atributo con attr()">
<img id="imagen" src="http://4.bp.blogspot.com/-dXgCUlaWcfY/T7Q0P04of1I/AAAAAAAAAeo/csmjFf-BY5c/s1600/jquery.png" width="180" height="180">
</body>
</html>




No hay comentarios: