Sie sind auf Seite 1von 4

Javascript Operators

The Javascript Document Object Model


Javascript suppor ts all of the usual operators :
Javascript refers to elements in an HTML document using the DOM.
• Arithmetic: + - * /
The root of the DOM is window.document, often abbreviated to just document.
• Increment / decrement: ++ --
• String: + (concatenation)
Within our document, we can refer to a hierarchy of named elements using a dotted
naming scheme, e.g. document.myform.val1. • Logical: && (and) || (or)
• Relational: == != < > <= >=
Elements can often be accessed in order as arrays, e.g. forms[] and elements[] • Array length: elements.length
below.

The input text boxes in a form have the special name value, and contain string
values. Convert these to integers using parseInt().

var v1 = parseInt(document.myform.val1.value);
var v2 = parseInt(document.myform.val2.value);

var no1 = parseInt(document.forms[0].elements[0].value);


var no2 = parseInt(document.forms[0].elements[1].value);
var no3 = parseInt(document.forms[0].elements[2].value);
- - javascript2 - 1 - © RMAP 2008 - - javascript2 - 2 - © RMAP 2008

Javascript Statements - 1 Javascript Statements - 2


Statements have a trailing semicolon: Conditional actions are controlled by the if ... then ... else statement:
s = "Hello World"; if ((name == "fred") && (a < 3))
x = a - b; { ...;
}
else
Loop using while() or for(): { ...;
while (x < 5) }
{ ...;
x = x + 1;
}

for (x = 0; x < 5; x++)


{ ...;
}

- - javascript2 - 3 - © RMAP 2008 - - javascript2 - 4 - © RMAP 2008


Identifying, Creating, Deleting and modifying HTML elements Identifying, Creating, Deleting and modifying HTML elements - 2
document.getElementById("two") We can create HTML elements, as well as text nodes.
generates a reference to the HTML element with the id="two" (not name="two" in
some browsers?).
Firstly, create an <input> element:
el = document.createElement("input");
document.getElementById("two").setAttribute("class","xxx");
takes this element and sets its "class" attribute to "xxx".
We must set its attributes separately:
document.createTextNode el.setAttribute ("type", "text");
("The sum of " + v1 + " and " + v2 + " is " + (v1+v2)); el.setAttribute ("name", "in"+count);
creates a text node, containing the specified string. el.setAttribute ("value", "in"+count);
count++;

document.getElementById("two").appendChild(textnode);
Then we store the new element into its container (a <form> element in this case).
sets the element text of element "two" to that specified by textnode.
node=document.getElementById("myform");
Bringing these together, using variables to store intermediate values: node.appendChild(el);
node = document.getElementById("xx");
newText = document.createTextNode ("Hello World");
node.appendChild(newText);

- - javascript2 - 5 - © RMAP 2008 - - javascript2 - 6 - © RMAP 2008

Identifying, Creating, Deleting and modifying HTML elements - 3 Identifying, Creating, Deleting and modifying HTML elements - 4
We can remove HTML elements that are referenced using the hierarchic notation: If we have multiple text nodes stored in a node, we can reference them in the array
node.childNodes[], e.g.
node=document.getElementById("myform");
node = document.getElementById("msgs");
while (node.childNodes.length > 0)
node.removeChild (node.in0);
{ node.removeChild (node.childNodes[0]);
}
Alternatively, we can identify an input node by ID. Notice that the node from which
We could also use while (node.hasChildNodes()) above.
the child is removed must be its immediate parent.
el = document.getElementById("in1");
node.removeChild (el);
We can also replace element text directly:
node = document.getElementById("msg");
newText = document.createTextNode ( "Hello" );
node.replaceChild(newText, node.childNodes[0]);

Notice that these programs (including extend.html) perform no error checking that
the elements exist before they try to delete them.

- - javascript2 - 7 - © RMAP 2008 - - javascript2 - 8 - © RMAP 2008


Identifying, Creating, Deleting and modifying HTML elements - 5 Identifying, Creating, Deleting and modifying HTML elements - 6
We can identify elements in part of a document by element (or tag) type: When creating non-HTML elements (e.g. SVG), we must create them in the correct
el = node.getElementsByTagName("td") namespace:

while (node.getElementsByTagName("*").length > 0) Create a <text> element:


{ node.removeChild (node.getElementsByTagName("*")[0]); var svgNS = "http://www.w3.org/2000/svg";
} el = document.createElementNS(svgNS, "text");

Beware that getElementsByTagName("*") does not return text nodes - use We set its attributes separately:
<span> around the text to make it accessible. el.setAttribute ("x", 400);
el.setAttribute ("y", 100);
el.setAttribute ("style", "font-size: "+fontSize);

We set the element text :


newText = document.createTextNode("words");

Then we inser t the textnode into the text element and store the new element into its
container (a <g> element in this case).
el.appendChild(newText);
node = document.getElementById("myGroup");
node.appendChild(el);

- - javascript2 - 9 - © RMAP 2008 - - javascript2 - 10 - © RMAP 2008

Validating Form Contents - 1 Validating Form Contents - 2


The onsubmit="return verify()" attribute of an HTML form element tells
Javascript to run the verify() function when the form submit button is pressed. function verify()
The verify() function should perform some tests, and report back to the form by { var a = document.forms[0].name.value);
returning true or false. The result returned should be true if the form fields are if (a == "Fred")
acceptable, or false otherwise. { return true;
}
The form input fields may be cleared using the reset() function. else
Notice the creation of an alert box when the form is cleared: { alert ("Sorry - Only Fred can run this!");
document.forms[0].reset();
return false;
}
}

...
<form action="http://www.computing.surrey.ac.uk/cgi-bin/R.Peel/getpost.pl"
method="post" onsubmit="return verify()">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>

- - javascript2 - 11 - © RMAP 2008 - - javascript2 - 12 - © RMAP 2008


Validating Form Contents - 3 Mouse and Keyboard Events
Form validation on the browser provides benefits: Traditionally, events were specified for specific elements:
• No ser ver CPU resource is used; <form action="http://localhost/cgi-bin/getpost.pl"
method="post" onsubmit="return verify()">
• The response to the user is faster.
<input type="text" size="2" onChange="status()">
On the other hand, security issues can only be addressed at the server:
<input class="noprint" name="button" type="button"
• The browser and server software may be modified out of sync - so the server
value="Add Row" onClick="addit()">
must defend itself regardless.
• The Javascript in the browser may be disabled, or fail. <a href="#" onmouseover="document.bgColor=’#a0c0e0’;"
• A malicious user might change the browser’s checking, in order intentionally to
pass bad data to the server. <a href="#" onmouseover="chg1();"
Avoidance is primarily through performing secondar y checks on the server,
probably in addition to those provided usefully by the browser.

- - javascript2 - 13 - © RMAP 2008 - - javascript2 - 14 - © RMAP 2008

Mouse and Keyboard Events - 2


It is also possible to assign events in Javascript itself [from www.quirksmode.org]:
var x = document.getElementsByTagName(’DIV’);
for (var i=0;i<x.length;i++) {
x[i].onmouseover = over;
x[i].onmouseout = out;
}

function over() {
this.style.backgroundColor=’#cc0000’
}

function out() {
this.style.backgroundColor=’#ffffff’
}

Don’t use x[i].onmouseover = over(); above - you will run the over()
function before installing its result in the onmouseover location within x[i].
Without the brackets, you install a reference to the function that only runs when the
mouse event takes place.

- - javascript2 - 15 - © RMAP 2008

Das könnte Ihnen auch gefallen