Download presentation
Presentation is loading. Please wait.
1
The Internet 11/15/11 Handling Data in JavaScript
CIS 228 The Internet 11/15/11 Handling Data in JavaScript
2
Attaching JavaScript to XHTML
<script> element (in <head>) Attribute: type=”text/javascript” Event attributes of elements (in <body>) Attribute: onload=”action” Action executes when page loads Attribute: onclick=”action” Action executes when mouse clicks element Attribute: onblur=”action” Action executes when mouse stops hovering
3
JavaScript Functions Reusable chunks of code to accomplish common tasks Built in functions alert('hello world'); Displays text in a pop up window prompt('first message', 'second message'); Solicits data from user Example <body onload=“alert('hello world');”> User defined functions Bundle together small tasks into bigger ones
4
More JavaScript Functions
<script type=“text/javascript”> function touchRock() { var userName = prompt(“Your name is?” “Enter name.”); if (userName) { alert(“Hi, ” + userName); document.getElementById(“rockImg”).src = rock_happy.png; } </script>
5
JavaScript Data Types String (text)
(e.g. “this is a string”, 'so is this', 'don\'t worry') Number Integer (e.g., 23, 0, -37) Decimal (e.g., , , ) Boolean true or false Object (e.g., document)
6
JavaScript Locations Associate a name with a value
Variable – the value may change Declaration: var s = “The user name is ”; Use: s = s + userName; Constant – the value is fixed Warning: constants may not be supported by IE Declaration: const userName = “malcolmX”; Values have types; locations do not! Declarations should initialize locations
7
JavaScript Identifiers
Identifiers name functions and locations Rules: 1 or more characters First character must be: letter or “_” or “$” All characters must be: letter or digit or “_” or “$” Spaces and other special characters are not allowed Camel case convention (for variables) thisIsACamelCaseVariableId Upper case convention (for constants) THIS_IS_AN_UPPER_CASE_CONSTANT_ID
8
JavaScript Expressions
String operator: + (concatination) e.g., s + userName, “Bowen” + “ ” + “Alpern” Numeric operators: +, -, *, /, % e.g., 3+4, 3-4, 3*4, 3/4, 3%4, 3.14*r*r/2 Comparison operators: ==, !=, <, <=, >, >= e.g., 3+4 != 8, 4/2 == 2, userName == “malcolmX” Boolean operators: !, &&, || e.g., !done && ((3*x+7<21 || 5>2*x || x==0)) e.g., s==“done” || !(name!=“Bowen” && s==“first”)
9
JavaScript Conversions
Error values: undefined – uninitialized locations (always initialize) NaN – not a number (e.g., 'sam' / 3 == NaN) Automatic conversions “6” + “3” == “6” + 3 == 6 + “3” == “63” == 63 != 6 + 3 “12” / “6” == “12” / 6 == 12 / “6” == 12 / 6 == 2 Explicit conversions ParseInt(“6”) + parseInt(“3”) == == 9 ParseFloat(“3.14”) + parseInt(“2”) == 5.14
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.