Introducción a Java Script
Después de haber aprendido como funciona un Servlets, JSP, Filters, Web Listeners, acceso a datos con Java. Vamos a aprender a utilizar diferentes tecnologías Web para enriquecer nuestras aplicaciones.En este Post vamos a ver sobre Java Script utilizando un Tutorial de W3 Schools.
Introducción
Java script es un lenguaje ligero de utilizar, que se puede colocar en páginas Web y puede ser ejecutado en Navegadores de Internet(Browser), Java Script es Fácil de Aprender.Como utilizar
Se utiliza en el HTML con la etiqueta html <script>
<script>
alert("My First JavaScript");
</script>
Se puede hacer referencias de recursos javascript externos, mediante un URL
Example
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
Probar
Salida
Java Script se utiliza para manipular elementos HTML en una páginaPara acceder a los elementos Java Script se utiliza un objeto implicito "document" y el método "getElementById"
document.getElementById(id)
Example
Cambiar contenido de un Html específico:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo">My First Paragraph</p>
<script>
document.getElementById("demo").innerHTML="My First JavaScript";
</script>
</body>
</html>
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo">My First Paragraph</p>
<script>
document.getElementById("demo").innerHTML="My First JavaScript";
</script>
</body>
</html>
Try it yourself »
Example
Escribir en el HTML
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
document.write("<p>My First JavaScript</p>");
</script>
</body>
</html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
document.write("<p>My First JavaScript</p>");
</script>
</body>
</html>
Try it yourself »
Sentencias
Las sentencias javascript son "comandos" para el Browser, Cada sentencia es una orden de que tiene que hacer el Browser.
document.getElementById("demo").innerHTML="Hello Dolly";
Normalmente, se necesita terminar la sentencia con ";"
Example
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
document.getElementById("myDIV").innerHTML="How are you?";
Try it yourself »
Bloques
Los Bloques están marcados por "{" y finaliza con "}" así como en el lenguaje de programación "Java"Example
function myFunction()
{
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
}
{
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
}
Try it yourself »
JavaScript es Sensible a las Mayúsculas
Es importante saber que los nombres de funciones, variables, etc. son sencibles a las Mayúscula.
ejemplo
var hola = null;
Hola = 1;
Hola y hola son nombres de diferentes y hola no es igual 1
Comentarios
Comentario simpleExample
// Write to a heading:
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
// Write to a paragraph:
document.getElementById("myP").innerHTML="This is my first paragraph.";
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
// Write to a paragraph:
document.getElementById("myP").innerHTML="This is my first paragraph.";
Try it yourself »
Comentario Multilinea
Example
/*
The code below will write
to a heading and to a paragraph,
and will represent the start of
my homepage:
*/
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
The code below will write
to a heading and to a paragraph,
and will represent the start of
my homepage:
*/
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
Try it yourself »
Example
var x=5; // declare x and assign 5 to it
var y=x+2; // declare y and assign x+2 to it
var y=x+2; // declare y and assign x+2 to it
Try it yourself »
Variables
Se utiliza la palabra reservada var para declarar una variable, esa variable tendrá un alcance o vida en la misma o dentro de una sentencia o bloque.
Example
<p id="demo"></p>
var carname="Volvo";
document.getElementById("demo").innerHTML=carname;
var carname="Volvo";
document.getElementById("demo").innerHTML=carname;
Try it yourself »
var lastname="Doe", age=30, job="carpenter";
var lastname="Doe",
age=30,
job="carpenter";
age=30,
job="carpenter";
var carname; //is undefined
Tipos de Datos
Las variables son de tipo dinámicoExample
var x; // Ahora x es undefined
var x = 5; // Ahora x es un Number
var x = "John"; // Ahora x es un String
var x = 5; // Ahora x es un Number
var x = "John"; // Ahora x es un String
Declaración de String
Example
var carname="Volvo XC60";
var carname='Volvo XC60';
var carname='Volvo XC60';
Example
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
Try it yourself »
Declaración de Números
Example
var x1=34.00; // con Decimales
var x2=34; // sin Decimales
var x2=34; // sin Decimales
Declaración de Booleanos
var x=true;
var y=false;
var y=false;
Arreglos en Java Script
var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
var cars=new Array("Saab","Volvo","BMW");
Objetos
var person={firstname:"John", lastname:"Doe", id:5566};
Example
name=person.lastname;//asignar apellido de persona en name
name=person["lastname"];//asignar también apellido en name
name=person["lastname"];//asignar también apellido en name
Try it yourself »
Undefined y Null
Example
cars=null;
person=null;
person=null;
Try it yourself »
Objetos
Casi todo en JavaScript puede ser un Object: Strings, Functions, Arrays, Dates.Creando un Objeto
Example
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
Try it yourself »
Acceder a Propiedades de String
var message="Hello World!";
var x=message.length;
var x=message.length;
Invocar Métodos de Objetos
objectName.methodName()Funciones
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
xample
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
Try it yourself »
Operadores
Operadores Aritméticos
Given that y=5, the table below explains the arithmetic operators:
Operator | Description | Example | Result of x | Result of y | Try it |
---|---|---|---|---|---|
+ | Addition | x=y+2 | 7 | 5 | Try it » |
- | Subtraction | x=y-2 | 3 | 5 | Try it » |
* | Multiplication | x=y*2 | 10 | 5 | Try it » |
/ | Division | x=y/2 | 2.5 | 5 | Try it » |
% | Modulus (division remainder) | x=y%2 | 1 | 5 | Try it » |
++ | Increment | x=++y | 6 | 6 | Try it » |
x=y++ | 5 | 6 | Try it » | ||
-- | Decrement | x=--y | 4 | 4 | Try it » |
x=y-- | 5 | 4 | Try it » |
Operadores de Asignación
Given that x=10 and y=5, the table below explains the assignment operators:
Operator | Example | Same As | Result | Try it |
---|---|---|---|---|
= | x=y | x=5 | Try it » | |
+= | x+=y | x=x+y | x=15 | Try it » |
-= | x-=y | x=x-y | x=5 | Try it » |
*= | x*=y | x=x*y | x=50 | Try it » |
/= | x/=y | x=x/y | x=2 | Try it » |
%= | x%=y | x=x%y | x=0 | Try it » |
Example
Concatenar 2 o más Cadenas de Texto.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
txt2="nice day";
txt3=txt1+txt2;
The result of txt3 will be:
What a verynice day
Try it yourself »
Example
x=5+5;
y="5"+5;
z="Hello"+5;
y="5"+5;
z="Hello"+5;
The result of x,y, and z will be:
10
55
Hello5
55
Hello5
Try it yourself »
Condicionantes
Operadores
Given that x=5, the table below explains the comparison operators:
Operator | Description | Comparing | Returns | Try it |
---|---|---|---|---|
== | equal to | x==8 | false | Try it » |
x==5 | true | Try it » | ||
=== | exactly equal to (equal value and equal type) | x==="5" | false | Try it » |
x===5 | true | Try it » | ||
!= | not equal | x!=8 | true | Try it » |
!== | not equal (different value or different type) | x!=="5" | true | Try it » |
x!==5 | false | Try it » | ||
> | greater than | x>8 | false | Try it » |
< | less than | x<8 | true | Try it » |
>= | greater than or equal to | x>=8 | false | Try it » |
<= | less than or equal to | x<=8 | true | Try it » |
Operadores Lógicos
Given that x=6 and y=3, the table below explains the logical operators:
Operator | Description | Example |
---|---|---|
&& | and | (x < 10 && y > 1) is true |
|| | or | (x==5 || y==5) is false |
! | not | !(x==y) is true |
Operador Condicional
Example
Example
If the variable age is a value below 18, the value of the variable voteable will be "Too young, otherwise the value ofvoteable will be "Old enough":
voteable=(age<18)?"Too young":"Old enough";
Try it yourself »
Sentencia IF
if (condition)
{
code to be executed if condition is true
}
{
code to be executed if condition is true
}
Example
Make a "Good day" greeting if the time is less than 20:00:
if (time<20)
{
x="Good day";
}
{
x="Good day";
}
The result of x will be:
Good day
Try it yourself »
Sentencia IF ELSE
Example
If the time is less than 20:00, you will get a "Good day" greeting, otherwise you will get a "Good evening" greeting
if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
{
x="Good day";
}
else
{
x="Good evening";
}
The result of x will be:
Good day
Sentencia IF ELSE ELSE
Example
If the time is less than 10:00, you will get a "Good morning" greeting, if not, but the time is less than 20:00, you will get a "Good day" greeting, otherwise you will get a "Good evening" greeting:
if (time<10)
{
x="Good morning";
}
else if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
{
x="Good morning";
}
else if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
The result of x will be:
Good day
Try it yourself »
Try it yourself »
Loops o Ciclos
ForYou can write:
for (var i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
}
{
document.write(cars[i] + "<br>");
}
Try it yourself »
FOR IN
The For/In Loop
The JavaScript for/in statement loops through the properties of an object:
Example
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
txt=txt + person[x];
}
for (x in person)
{
txt=txt + person[x];
}
Try it yourself »
While
Do While
Breaks
Errores
Manejo de Excepciones
Example
<!DOCTYPE html>
<html>
<head>
<script>
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()">
</body>
</html>
<html>
<head>
<script>
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()">
</body>
</html>
Try it yourself »
Validaciones
Ejemplo de Validación
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
The function above could be called when a form is submitted:
Example
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Try it yourself »
Documento de Referencia de HTML DOM http://www.w3schools.com/jsref/default.asp
No hay comentarios:
Publicar un comentario