childNodes[]
firstChild[] lastChild[]
BODY
DIV UL
LI LILI
parentNodes[]
previousSibling previousSibling
nextSibling nextSibling
firstElementChild
lastElementChild
nextElementSibling
previousElementSibling
getElementsByTagName
getElementById
getElementsByClassName
http://webclass.polyn.kiae.su/classes/homef.htm
Значения свойств:
href: http://webclass.polyn.kiae.su/classes/homef.htm
protocol: http:
hostname: webclass.polyn.kiae.su
host: webclass.polyn.kiae.su:80
port: 80
pathname: classes/homef.htm
search:
hash:
Обращение к свойству объекта класса URL:
имя_объект_класса_URL.свойство
Например, так:
document.links[0].href
document.location.host
document.links[2].hash
Обрщение к свойству объекта класса
URL: & location
g_reEmail = /^[w.=-]+@[w.-]+.[a-z]{2,4}$/;
распознание
строки
EVENT
DOM
ШПОРА
chrome dev tool hotkeys
grouping
RegExp - object <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />
<title>Регулярные выражения</title>
<script type="text/javascript">
function f(){
var a = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,4})+$/;
var inp = document.getElementById('inp');
var verno = document.getElementById('verno');
var neverno = document.getElementById('neverno');
if(inp.value.search(a) !== -1){
verno.style.display = 'inline';
neverno.style.display = 'none';
}
else{
neverno.style.display = 'inline';
verno.style.display = 'none';
}
}
</script>
</head>
<body>
<input type="text" id="inp"/>
<div style="display:none; color:#00FF00" id="verno">Верно</div>
<div style="display:none; color:red" id="neverno">Неверно</div><br />
<input type="button" value="Отправить" onclick="f()"/>
</body>
</html>
sub = s.substring(1,4);
last_char = s.charAt(s.length – 1) - last_char = s[s.length – 1];
i = s.indexOf('a');
var string_value = String(number);
string_value = number.toString( );
var u = s.toUpperCase();
if (/[^a-zа-яs]+/gi.test(text_val)) {
$('#username_message').
text('не допустимый символ').
removeClass('mess_ok').
addClass('mess_error');
}
text_val - это вал инпута
рэг дает список не допустимых
символов, а тэст ищет эти не
допустимые
strToTest.match(/^(d{5}(-d{4})?$)|wow$/
strToTest.match(/^[a-zA-Z0-9]+$/) != null
countMatches(document.getElementById('sourceText').innerHTML,/javascript/i, 10);
function countMatches(sourceString, patternToFind, patLength) {
var result=0, pos=0;
var tempString = new String(sourceString);
while ((pos = tempString.search(patternToFind)) != -1) {
result++;
pos += patLength;
tempString = tempString.substr(pos);
}
alert("Pattern was found " + result + " times!");
}
function findMatchesWithExec(sourceString, patternToFind) {
var result;
while ((result = patternToFind.exec(sourceString)) != null) {
alert("Found a match: " + result[0] + " at position: " + result.index +
"; will search next starting at: " + patternToFind.lastIndex +
"nThe exchange part was: " + result[1] +
"nThe rest of the number was: " + result[2]);
}
}
function doExec() {
findMatchesWithExec(document.getElementById('sourceText').innerHTML,/(d{3})-(d{4})/g);
}
function findMatchesGlobal(sourceString, patternToFind) {
var result = sourceString.match(patternToFind);
alert("Found a total of " + result.length + " matches: " + result.join(", "));
}
function findMatchesNonGlobal(sourceString, patternToFind) {
var result = sourceString.match(patternToFind);
alert("Found a match: " + result[0] + "nThe exchange part was: " + result[1] + "nThe rest of the number was: " + result[2]);
}
function doGlobalMatch() {
findMatchesGlobal(document.getElementById('sourceText').innerHTML,/(d{3})-(d{4})/g);
}
function doNonGlobalMatch() {
findMatchesNonGlobal(document.getElementById('sourceText').innerHTML,/(d{3})-(d{4})/);
}
function replaceString(sourceString, patternToFind, strReplacement) {
var result = sourceString.replace(patternToFind,strReplacement);
document.getElementById('sourceText').innerHTML = result;
}
function replaceWithFunction(sourceString, patternToFind) {
var result = sourceString.replace(patternToFind,function() {
return "JavaScript"+gCount++;
});
document.getElementById('sourceText').innerHTML = result;
}
function doReplacement() {
replaceString(document.getElementById('sourceText').innerHTML,/javascript/gi,"JavaScript");
replaceWithFunction(document.getElementById('sourceText').innerHTML,/javascript/gi,"JavaScript");
}
var gCount=0;
match
test()
exec()
STRING
search
replace
WINDOWS.close();
WINDOWS.focus();
ЗАПУСТИТЬ/ОСТАНОВИТЬ поток
open("URL","window_name","param,...",replace);
где -URL - страница, которая будет загружена в новое окно,
window_name - имя окна, которое можно использовать в
атрибуте target в контейнерах A и FORM,
replace - позволяет при открытии окна управлять записью в
массив history
window.close();
self.close();
window.opener.close();
id=window.open();
...id.close();
function myfocus(a) {
id = window.open ("","example", "scrollbars, width=300, height=200");
if(a==1) {
id.document.open();
id.document.write("<center>Открыли окно в первый раз"); }
if(a==2) {
id.document.open();
id.document.write("<center>Открыли окно во второй раз"); }
if(a==3) {
id.focus();
id.document.open();
id.document.write("<center>Открыли окно во второй раз"); }
id.document.write("<form><input type=button
onClick='window.close();' value='Закрыть окно'></center>");
id.document.close();
}
Методы объекта Location
assign(url) - загрузить документ по данному url
reload([forceget]) - перезагрузить документ по текущему URL. Аргумент forceget - булево значение,
если оно true, то документ перезагружается всегда с сервера, если false или не указано, то браузер
может взять страницу из своего кэша.
replace(url) - заменить текущий документ на документ по указанному url. Разница, по сравнению с
assign() заключается в том, что после использования replace() - страница не записывается в истории
посещений. В частности, это значит, что посетитель не сможет использовать для возврата кнопку
браузера "Назад".
toString() - возвращает строковое представление URL для объекта Location
var idp1 = null;
function start() {
d = new Date();
window.document.c1.f1.value =
d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
idp1=setTimeout("start();",500); }
function stop() {
clearTimeout(idp1);idp1=null; }
...
<form name=c1>
Текущее время:<input name=f1 size=8>
<input type=button value="Start" onClick="if(idp1==null)start();">
<input type=button value="Stop" onClick="if(idp1!=null)stop();">
</form>
WINDOWS.STATUS
WINDOWS.LOCATION
WINDOWS.HISTORY
WINDOWS.NAVIGATOR
Программируем status:
<a href="#status" onMouseover="window.status='Jump to status description';return true;" onMouseout="window.status='Status bar programming';return true;">window.status</a>
Программируем DefaultStatus:
<body onLoad="window.defaultStatus='Status bar programming';">
<script type="text/javascript">
window.status="Some text in the status bar!!";
</script>
Свойства location:
http://kuku.ru:80/r/dir/page?search#mark
Методы location:
window.location.reload(true);
window.location.replace('#top');
<form>
<input type=button value=Назад onClick=history.back()>
</form>
<form><input type=button value="Тип навигатора" onClick="window.alert(window.navigator.userAgent);">
</form>
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506)
<script>
if(navigator.mimeTypes['image/gif']!=null) document.write("Ваш браузер поддерживает GIF<br>");
if(navigator.mimeTypes['image/kuku']==null) document.write("Ваш браузер не поддерживает KUKU");
</script>
onclick="top.location.href='1.html';" /
<input
type="button"
value="Перейти на страницу 1.html в текущем фрейме"
onclick="self.location.href='1.html';" />
<input
type="button"
value="Перейти на страницу 1.html в текущем фрейме"
onclick="top.frames['имя фрейма'].location.href='1.html';" />
NAVIGATOR HYSTORY SCREEN LOCATION DOCUMENT
forms[] anchors[] links[] images[]
опр. тип браузера urlэкранистория
открытый документ
alert()
confirm()
prompt()
open()
close()
focus()
setTimeout()
clearTimeout()
scroll()
blur()
confirm()
окно ДА/НЕТ
(return true/false )
prompt()
ввод значения в
выпадаюшем окне
window.print();
windpw.open(”hello.html”);
остановка стандартного событияe.preventDefault();Event.stop(event);
events
media
function addEventHandler(oNode, evt, oFunc, bCaptures)
{
if (typeof(window.event) != "undefined")
oNode.attachEvent("on"+evt, oFunc);
else
oNode.addEventListener(evt, oFunc, bCaptures);
}
function removeEventHandler(oNode, evt, oFunc, bCaptures) {
if (typeof (window.event) != "undefined")
oNode.detachEvent("on" + evt, oFunc);
else
oNode.removeEventListener(evt, oFunc, bCaptures);
}
function getEventTarget(e) {
if (window.event) return window.event.srcElement;
else return e.target;
}
function onLinkClicked(e) {
alert("You clicked the link!");
}
function onEnableClick(e) {
var target = getEventTarget(e);
if (target.checked)
addEventHandler(document.getElementById("clickLink"), "click",
onLinkClicked, false);
else
removeEventHandler(document.getElementById("clickLink"),
"click", onLinkClicked, false);
}
function setUpClickEvent(e) {
addEventHandler(document.getElementById("Checkbox1"), "click",
onEnableClick, false);
}
addEventHandler(window, "load", setUpClickEvent, false);
function addEventHandler(oNode, evt,
oFunc, bCaptures)
{
if (typeof(window.event) != "undefined")
oNode.attachEvent("on"+evt, oFunc);
else
oNode.addEventListener(evt, oFunc,
bCaptures);
}
function removeEventHandler(oNode, evt,
oFunc, bCaptures) {
if (typeof (window.event) != "undefined")
oNode.detachEvent("on" + evt, oFunc);
else
oNode.removeEventListener(evt, oFunc,
bCaptures);
}
function getEventTarget(e) {
if (window.event) return
window.event.srcElement;
else return e.target;
}
addEventHandler(document.getElementsByTagName("body")[0],"click",bodyHandler,true);
function bodyHandler(evt) {
var e = evt || window.event;
var target = getEventTarget(e);
var str = "Event handler for body, target: " + target.getAttribute('id') + " , type: " + e.type;
if (e.eventPhase) str+=" ; phase: " + e.eventPhase;
alert(str);
}
events
What is the type
of the event?
Which HTML element is the
target of the event?
Which HTML element is the
target of the event?
Right click
function doSomething(e) {
if (!e) var e = window.event;
alert(e.type);
}
W3C/Netscape says: the target. No, says Microsoft, the srcElement.
Both properties return the HTML element the event took place on.
function doSomething(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
}
function doSomething(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
alert('Character was ' + character);
}
function doSomething(e) {
var rightclick;
if (!e) var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert('Rightclick: ' + rightclick); // true or false
}
Mouse position
1. clientX,clientY
2. layerX,layerY
3. offsetX,offsetY
4. pageX,pageY
5. screenX,screenY
6. x,y
Correct script
This is the correct script for detecting the mouse coordinates:
function doSomething(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
// posx and posy contain the mouse position relative to the document
// Do something with this information
}
http://www.quirksmode.org/js/events_properties.html
// Get the element, add a click listener...
document.querySelector('#parent-list').addEventListener('click', function(e) {
// e.target is the clicked element!
// If it was a list item
if(e.target && e.target.tagName == 'LI') {
// List item found! Do something now!
}
});
COOKIES
<form> <input type=button value="Показать Cookies" onClick="window.alert(window.document.cookie);"> </form>
function change_cookies() {
a = new Array();
c = new Date();
a = document.cookie.split(';');
document.cookie=a[0]+"; expires="+c.toGMTString()+";"
window.alert(document.cookie);
...
<form>
<input type=button value="Чтобы не хранить этот хлам вечно" onClick="change_cookies()">
</form>
function asign()
{
document.cookie="n1=3";
window.alert(document.cookie);
}
...
<form>
<input type=button value="Изменить n1" onClick="asign()">
</form>
<form>
<input type=button value="Показать Cookies" onClick="window.alert(window.document.cookie);">
</form>
<style type="text/css">
div{
padding-bottom:5px;
}
</style>
<script type="text/javascript">
function f(){
var namecom = document.getElementById('namecom');
var email = document.getElementById('email');
var site = document.getElementById('site');
document.cookie = 'namecom=' + encodeURIComponent(namecom.value) + '; max-age=' + (365*24*60*60) + '; path=/';
document.cookie = 'email=' + encodeURIComponent(email.value) + '; max-age=' + (365*24*60*60) + '; path=/';
document.cookie = 'site=' + encodeURIComponent(site.value) + '; max-age=' + (365*24*60*60) + '; path=/';
}
function opencookie(par){
var allcookies = document.cookie;
var pos = allcookies.indexOf(par);
var dlina = par.length;
if(pos !== -1){
var start = pos + dlina + 1;
var end = allcookies.indexOf(';', start);
if (end == -1)
end = allcookies.length;
var znachenie = allcookies.substring(start, end);
znachenie = decodeURIComponent(znachenie);
this.cooka = znachenie;
}
}
function z(){
alert('Содержимое cookies' + document.cookie);
if (document.cookie !== ''){
var namecomcooka = new opencookie('namecom');
alert(namecomcooka.cooka);
var emailcooka = new opencookie('email');
alert(emailcooka.cooka);
var sitecooka = new opencookie('site');
alert(sitecooka.cooka);
var namecom = document.getElementById('namecom');
var email = document.getElementById('email');
var site = document.getElementById('site');
namecom.value = namecomcooka.cooka;
email.value = emailcooka.cooka;
site.value = sitecooka.cooka;
}
}
</script>
</head>
<body onload="z()">
<p>Форма с полями ввода:</p>
<div><input type="text" id="namecom"/> Имя</div>
<div><input type="text" id="email"/> E-mail</div>
<div><input type="text" id="site"/> Сайт</div>
<div><input type="button" value="Отправить" onclick="f()"/></div>
</body>
document.querySelector or document.querySelectorAll
ООП
Объекты
extending
Array.prototype.longestElement =
function() {
var maxLength = 0;
for (var i=0; i < this.length; i++) {
if (this[i].toString().length > maxLength)
maxLength = this[i].toString().length;
}
return maxLength;
}
inheritancefunction Rectangle(w,h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function() {
return (this.width * this.height);
}
Rectangle.prototype.toString = function() {
return "Rectangle of width: " + this.width + " and height: " + this.height;
}
Rectangle.prototype.valueOf = function() {
return this.area();
}
Rectangle.prototype.equals = function(oRect) {
return (this.width == oRect.width && this.height == oRect.height);
}
Rectangle.prototype.compareTo = function(oRect) {
return (this.area() - oRect.area());
}
function DepthRectangle(w,h,d) {
Rectangle.call(this,w,h);
this.depth = d;
}
DepthRectangle.prototype = new Rectangle();
DepthRectangle.prototype.constructor = DepthRectangle;
DepthRectangle.prototype.volume = function() {
return (this.area() * this.depth);
}
DepthRectangle.prototype.toString = function() {
return "DepthRectangle with width: " + this.width + " & height: " + this.height + " & depth: " + this.depth;
}
var myRect = new Rectangle(5,6);
var myDeepRect = new DepthRectangle(7,8,9);
alert(myDeepRect.volume());
alert(myDeepRect.area());
alert(myRect instanceof DepthRectangle);
function Bird(name) {
this.name = name;
}
Bird.prototype.flighted = true; // Default for all Birds
Bird.prototype.isFlighted = function () { return this.flighted };
Bird.prototype.getName = function () { return this.name };
function Chicken(name) {
// Chain the constructors
Chicken.superclass.constructor.call(this, name);
}
приятно
знать
function include(file,scriptStack) {
var script = document.createElement('script');
script.src = file;
script.type = 'text/javascript';
if(scriptStack == 'async' && elemHasAttribute('script','async'))
script.async = true;
else if(scriptStack == 'defer')
script.defer = true;
document.getElementsByTagName('head')[0].appendChild(script);
debuggStack({'msg':'script.js(47): include '+file});
};
//Include js file with callback function
function includeWithCallBack(file, callback) {
var script = document.createElement('script');
script.src = file;
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
script.onreadystatechange = function() {
if(script.readyState == "complete" || script.readyState=="loaded") {
script.onreadystatechange = false;
callback;
} else {
script.onload = function() {
callback;
};
}
};
};
function elemHasAttribute(elementName,attribute){
var element = document.createElement(elementName);
return attribute in element;
};
HTML5 feature detection
Include script
Cheack attribute
function hasColorSupport(){
input = document.createElement("input" );
input.setAttribute("type" , "color" );
var hasColorType = (input.type !== "text" );
// handle Safari/Chrome partial implementation
if(hasColorType){
var testString = "foo" ;
input.value=testString;
hasColorType = (input.value != testString);
}
return(hasColorType);
}`
function hasAutofocus() {
var element = document.createElement('input' );
return 'autofocus' in element;
}
$(function(){
if(!hasAutofocus()){
$('input[autofocus=true]' ).focus();
}
});
var frag = document.createDocumentFragment();
local & Session
storage $.fn.autosave = function(prefix){
var storage = localStorage; // or sessionStorage
var $this = $(this);
if(!prefix){ prefix = $this.attr('id'); }
prefix += ">"; // Separate prefix from input name;
function save(){
console.log('save')
$this.find('input:not(:password,
:submit)').each(function(index, element){
var key = prefix + element.name;
storage.setItem(key, $(element).val());
})
};
function restore(){
var i, key, value, name;
for(i=0; i < storage.length; i++){
key = storage.key(i);
if(0 === key.indexOf(prefix)){
value = storage.getItem(key);
name = key.replace(prefix, '');
$this.find('[name='+name+']').val(value);
}
}
};
function clear(e){
var keys = [], i, key;
// Collect Keys;
for(i=0; i < storage.length; i++){
key = storage.key(i);
if(0 === key.indexOf(prefix)){
keys.push(key);
}
}
// Remove Each Key
for(i=0; i < keys.length; i++ ){
storage.removeItem(keys[i]);
}
};
$this.change(save);
$this.submit(clear);
restore();
console.log('DONE')
$(document).ready(function() {
if (window.localStorage) {
var fromDb = localStorage.getItem("courses");
if (fromDb) {
// Read the courses from local storage, into the
global "courses" array.
courses = JSON.parse(fromDb);
}
else {
// Store the global "courses" array into local
storage.
storeCourses();
}
}
});
// Stores the global "courses" array into local
storage.
function storeCourses() {
if (window.localStorage) {
localStorage.setItem("courses",
JSON.stringify(courses));
}
}
HTML5 REF
Events
style
origin
Elems
Elems Attr
DOM
Exeptions
Categories
©Trybynenko Andrii

More Related Content

PDF
第二节课:html5 – web开发步入新阶段
PDF
Tai Lieu Javascript
PPTX
EWD 3トレーニングコース#13 全てをひとつにまとめてewd-xpressで稼働させてみる
PDF
Web components v1 intro
PDF
jQuery for beginners
PDF
Macdom html preprocesor
PPTX
Service Workers
PPTX
Templating en JavaScript
第二节课:html5 – web开发步入新阶段
Tai Lieu Javascript
EWD 3トレーニングコース#13 全てをひとつにまとめてewd-xpressで稼働させてみる
Web components v1 intro
jQuery for beginners
Macdom html preprocesor
Service Workers
Templating en JavaScript

What's hot (19)

PDF
Node.js をさりげなく取り入れた 最近のフロントエンド事情について
PPTX
Jquery Introduction Hebrew
PDF
Meteor로 만드는 modern web application
PDF
twMVC#20 | 前端視覺化實戰 - D3.js
PDF
Desain kerangka awal
PDF
Intro to jQuery UI
PPTX
лабораторная работа 1 Исправленная
PPTX
React - podsumowanie z placu boju
PDF
tmn - Introdução ao DOM
PDF
Tugas uts
PDF
jQuery プラグイン作成入門
TXT
PDF
Workshop Teknis Javascript SMK Telkom Sandhy Putra Malang
PPTX
Tjejer kodar 100 - Dag 2 - HTML & CSS
PDF
Offline-Strategien für HTML5Web Applikationen - WMMRN12
ODP
Des Templates Heiliger Gral
PDF
Hands-On Java web passando por Servlets, JSP, JSTL, JDBC, Hibernate, DAO, MV...
TXT
nose ponerle
PDF
Web Components und Polymer: Klassen für das Web
Node.js をさりげなく取り入れた 最近のフロントエンド事情について
Jquery Introduction Hebrew
Meteor로 만드는 modern web application
twMVC#20 | 前端視覺化實戰 - D3.js
Desain kerangka awal
Intro to jQuery UI
лабораторная работа 1 Исправленная
React - podsumowanie z placu boju
tmn - Introdução ao DOM
Tugas uts
jQuery プラグイン作成入門
Workshop Teknis Javascript SMK Telkom Sandhy Putra Malang
Tjejer kodar 100 - Dag 2 - HTML & CSS
Offline-Strategien für HTML5Web Applikationen - WMMRN12
Des Templates Heiliger Gral
Hands-On Java web passando por Servlets, JSP, JSTL, JDBC, Hibernate, DAO, MV...
nose ponerle
Web Components und Polymer: Klassen für das Web
Ad

Viewers also liked (20)

PDF
Boletim Sindibeb-BA 488
PDF
Sindibeb nº 491
PDF
Sindibeb nº 490
PDF
Rede baiana de excelencia 2016 alagoinhas
PDF
481 pdf
PDF
Boletim Sindibeb-BA 484
PDF
Boletim Sindibeb-BA 479
PPT
BalançO Resumido Agreste Alagoinhas
PDF
SINDIBEB/BA 464
PDF
Relatório gestão fbtm 2014
PDF
Sindibeb nº 499
PPTX
Rio Corrente - Diálogos Territoriais
PPT
Biogeografia 10
PDF
Sindibeb ba 493
PPT
Domínios Morfoclimáticos
PPT
Perfil Do Territorio Agreste De Alagoinhas 2009[1]
PPTX
Domínio morfoclimático [recuperado]
PPTX
Dominio Mares e Morros
PDF
Domínios mares de morros
PPT
Domínios morfoclimáticos
Boletim Sindibeb-BA 488
Sindibeb nº 491
Sindibeb nº 490
Rede baiana de excelencia 2016 alagoinhas
481 pdf
Boletim Sindibeb-BA 484
Boletim Sindibeb-BA 479
BalançO Resumido Agreste Alagoinhas
SINDIBEB/BA 464
Relatório gestão fbtm 2014
Sindibeb nº 499
Rio Corrente - Diálogos Territoriais
Biogeografia 10
Sindibeb ba 493
Domínios Morfoclimáticos
Perfil Do Territorio Agreste De Alagoinhas 2009[1]
Domínio morfoclimático [recuperado]
Dominio Mares e Morros
Domínios mares de morros
Domínios morfoclimáticos
Ad

Lesson 01

  • 1. childNodes[] firstChild[] lastChild[] BODY DIV UL LI LILI parentNodes[] previousSibling previousSibling nextSibling nextSibling firstElementChild lastElementChild nextElementSibling previousElementSibling getElementsByTagName getElementById getElementsByClassName http://webclass.polyn.kiae.su/classes/homef.htm Значения свойств: href: http://webclass.polyn.kiae.su/classes/homef.htm protocol: http: hostname: webclass.polyn.kiae.su host: webclass.polyn.kiae.su:80 port: 80 pathname: classes/homef.htm search: hash: Обращение к свойству объекта класса URL: имя_объект_класса_URL.свойство Например, так: document.links[0].href document.location.host document.links[2].hash Обрщение к свойству объекта класса URL: & location g_reEmail = /^[w.=-]+@[w.-]+.[a-z]{2,4}$/; распознание строки EVENT DOM ШПОРА chrome dev tool hotkeys grouping RegExp - object <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1251" /> <title>Регулярные выражения</title> <script type="text/javascript"> function f(){ var a = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,4})+$/; var inp = document.getElementById('inp'); var verno = document.getElementById('verno'); var neverno = document.getElementById('neverno'); if(inp.value.search(a) !== -1){ verno.style.display = 'inline'; neverno.style.display = 'none'; } else{ neverno.style.display = 'inline'; verno.style.display = 'none'; } } </script> </head> <body> <input type="text" id="inp"/> <div style="display:none; color:#00FF00" id="verno">Верно</div> <div style="display:none; color:red" id="neverno">Неверно</div><br /> <input type="button" value="Отправить" onclick="f()"/> </body> </html> sub = s.substring(1,4); last_char = s.charAt(s.length – 1) - last_char = s[s.length – 1]; i = s.indexOf('a'); var string_value = String(number); string_value = number.toString( ); var u = s.toUpperCase(); if (/[^a-zа-яs]+/gi.test(text_val)) { $('#username_message'). text('не допустимый символ'). removeClass('mess_ok'). addClass('mess_error'); } text_val - это вал инпута рэг дает список не допустимых символов, а тэст ищет эти не допустимые strToTest.match(/^(d{5}(-d{4})?$)|wow$/ strToTest.match(/^[a-zA-Z0-9]+$/) != null countMatches(document.getElementById('sourceText').innerHTML,/javascript/i, 10); function countMatches(sourceString, patternToFind, patLength) { var result=0, pos=0; var tempString = new String(sourceString); while ((pos = tempString.search(patternToFind)) != -1) { result++; pos += patLength; tempString = tempString.substr(pos); } alert("Pattern was found " + result + " times!"); } function findMatchesWithExec(sourceString, patternToFind) { var result; while ((result = patternToFind.exec(sourceString)) != null) { alert("Found a match: " + result[0] + " at position: " + result.index + "; will search next starting at: " + patternToFind.lastIndex + "nThe exchange part was: " + result[1] + "nThe rest of the number was: " + result[2]); } } function doExec() { findMatchesWithExec(document.getElementById('sourceText').innerHTML,/(d{3})-(d{4})/g); } function findMatchesGlobal(sourceString, patternToFind) { var result = sourceString.match(patternToFind); alert("Found a total of " + result.length + " matches: " + result.join(", ")); } function findMatchesNonGlobal(sourceString, patternToFind) { var result = sourceString.match(patternToFind); alert("Found a match: " + result[0] + "nThe exchange part was: " + result[1] + "nThe rest of the number was: " + result[2]); } function doGlobalMatch() { findMatchesGlobal(document.getElementById('sourceText').innerHTML,/(d{3})-(d{4})/g); } function doNonGlobalMatch() { findMatchesNonGlobal(document.getElementById('sourceText').innerHTML,/(d{3})-(d{4})/); } function replaceString(sourceString, patternToFind, strReplacement) { var result = sourceString.replace(patternToFind,strReplacement); document.getElementById('sourceText').innerHTML = result; } function replaceWithFunction(sourceString, patternToFind) { var result = sourceString.replace(patternToFind,function() { return "JavaScript"+gCount++; }); document.getElementById('sourceText').innerHTML = result; } function doReplacement() { replaceString(document.getElementById('sourceText').innerHTML,/javascript/gi,"JavaScript"); replaceWithFunction(document.getElementById('sourceText').innerHTML,/javascript/gi,"JavaScript"); } var gCount=0; match test() exec() STRING search replace WINDOWS.close(); WINDOWS.focus(); ЗАПУСТИТЬ/ОСТАНОВИТЬ поток open("URL","window_name","param,...",replace); где -URL - страница, которая будет загружена в новое окно, window_name - имя окна, которое можно использовать в атрибуте target в контейнерах A и FORM, replace - позволяет при открытии окна управлять записью в массив history window.close(); self.close(); window.opener.close(); id=window.open(); ...id.close(); function myfocus(a) { id = window.open ("","example", "scrollbars, width=300, height=200"); if(a==1) { id.document.open(); id.document.write("<center>Открыли окно в первый раз"); } if(a==2) { id.document.open(); id.document.write("<center>Открыли окно во второй раз"); } if(a==3) { id.focus(); id.document.open(); id.document.write("<center>Открыли окно во второй раз"); } id.document.write("<form><input type=button onClick='window.close();' value='Закрыть окно'></center>"); id.document.close(); } Методы объекта Location assign(url) - загрузить документ по данному url reload([forceget]) - перезагрузить документ по текущему URL. Аргумент forceget - булево значение, если оно true, то документ перезагружается всегда с сервера, если false или не указано, то браузер может взять страницу из своего кэша. replace(url) - заменить текущий документ на документ по указанному url. Разница, по сравнению с assign() заключается в том, что после использования replace() - страница не записывается в истории посещений. В частности, это значит, что посетитель не сможет использовать для возврата кнопку браузера "Назад". toString() - возвращает строковое представление URL для объекта Location var idp1 = null; function start() { d = new Date(); window.document.c1.f1.value = d.getHours()+":"+d.getMinutes()+":"+d.getSeconds(); idp1=setTimeout("start();",500); } function stop() { clearTimeout(idp1);idp1=null; } ... <form name=c1> Текущее время:<input name=f1 size=8> <input type=button value="Start" onClick="if(idp1==null)start();"> <input type=button value="Stop" onClick="if(idp1!=null)stop();"> </form> WINDOWS.STATUS WINDOWS.LOCATION WINDOWS.HISTORY WINDOWS.NAVIGATOR Программируем status: <a href="#status" onMouseover="window.status='Jump to status description';return true;" onMouseout="window.status='Status bar programming';return true;">window.status</a> Программируем DefaultStatus: <body onLoad="window.defaultStatus='Status bar programming';"> <script type="text/javascript"> window.status="Some text in the status bar!!"; </script> Свойства location: http://kuku.ru:80/r/dir/page?search#mark Методы location: window.location.reload(true); window.location.replace('#top'); <form> <input type=button value=Назад onClick=history.back()> </form> <form><input type=button value="Тип навигатора" onClick="window.alert(window.navigator.userAgent);"> </form> Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506) <script> if(navigator.mimeTypes['image/gif']!=null) document.write("Ваш браузер поддерживает GIF<br>"); if(navigator.mimeTypes['image/kuku']==null) document.write("Ваш браузер не поддерживает KUKU"); </script> onclick="top.location.href='1.html';" / <input type="button" value="Перейти на страницу 1.html в текущем фрейме" onclick="self.location.href='1.html';" /> <input type="button" value="Перейти на страницу 1.html в текущем фрейме" onclick="top.frames['имя фрейма'].location.href='1.html';" /> NAVIGATOR HYSTORY SCREEN LOCATION DOCUMENT forms[] anchors[] links[] images[] опр. тип браузера urlэкранистория открытый документ alert() confirm() prompt() open() close() focus() setTimeout() clearTimeout() scroll() blur() confirm() окно ДА/НЕТ (return true/false ) prompt() ввод значения в выпадаюшем окне window.print(); windpw.open(”hello.html”); остановка стандартного событияe.preventDefault();Event.stop(event); events media function addEventHandler(oNode, evt, oFunc, bCaptures) { if (typeof(window.event) != "undefined") oNode.attachEvent("on"+evt, oFunc); else oNode.addEventListener(evt, oFunc, bCaptures); } function removeEventHandler(oNode, evt, oFunc, bCaptures) { if (typeof (window.event) != "undefined") oNode.detachEvent("on" + evt, oFunc); else oNode.removeEventListener(evt, oFunc, bCaptures); } function getEventTarget(e) { if (window.event) return window.event.srcElement; else return e.target; } function onLinkClicked(e) { alert("You clicked the link!"); } function onEnableClick(e) { var target = getEventTarget(e); if (target.checked) addEventHandler(document.getElementById("clickLink"), "click", onLinkClicked, false); else removeEventHandler(document.getElementById("clickLink"), "click", onLinkClicked, false); } function setUpClickEvent(e) { addEventHandler(document.getElementById("Checkbox1"), "click", onEnableClick, false); } addEventHandler(window, "load", setUpClickEvent, false); function addEventHandler(oNode, evt, oFunc, bCaptures) { if (typeof(window.event) != "undefined") oNode.attachEvent("on"+evt, oFunc); else oNode.addEventListener(evt, oFunc, bCaptures); } function removeEventHandler(oNode, evt, oFunc, bCaptures) { if (typeof (window.event) != "undefined") oNode.detachEvent("on" + evt, oFunc); else oNode.removeEventListener(evt, oFunc, bCaptures); } function getEventTarget(e) { if (window.event) return window.event.srcElement; else return e.target; } addEventHandler(document.getElementsByTagName("body")[0],"click",bodyHandler,true); function bodyHandler(evt) { var e = evt || window.event; var target = getEventTarget(e); var str = "Event handler for body, target: " + target.getAttribute('id') + " , type: " + e.type; if (e.eventPhase) str+=" ; phase: " + e.eventPhase; alert(str); } events What is the type of the event? Which HTML element is the target of the event? Which HTML element is the target of the event? Right click function doSomething(e) { if (!e) var e = window.event; alert(e.type); } W3C/Netscape says: the target. No, says Microsoft, the srcElement. Both properties return the HTML element the event took place on. function doSomething(e) { var targ; if (!e) var e = window.event; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ.nodeType == 3) // defeat Safari bug targ = targ.parentNode; } function doSomething(e) { var code; if (!e) var e = window.event; if (e.keyCode) code = e.keyCode; else if (e.which) code = e.which; var character = String.fromCharCode(code); alert('Character was ' + character); } function doSomething(e) { var rightclick; if (!e) var e = window.event; if (e.which) rightclick = (e.which == 3); else if (e.button) rightclick = (e.button == 2); alert('Rightclick: ' + rightclick); // true or false } Mouse position 1. clientX,clientY 2. layerX,layerY 3. offsetX,offsetY 4. pageX,pageY 5. screenX,screenY 6. x,y Correct script This is the correct script for detecting the mouse coordinates: function doSomething(e) { var posx = 0; var posy = 0; if (!e) var e = window.event; if (e.pageX || e.pageY) { posx = e.pageX; posy = e.pageY; } else if (e.clientX || e.clientY) { posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } // posx and posy contain the mouse position relative to the document // Do something with this information } http://www.quirksmode.org/js/events_properties.html // Get the element, add a click listener... document.querySelector('#parent-list').addEventListener('click', function(e) { // e.target is the clicked element! // If it was a list item if(e.target && e.target.tagName == 'LI') { // List item found! Do something now! } }); COOKIES <form> <input type=button value="Показать Cookies" onClick="window.alert(window.document.cookie);"> </form> function change_cookies() { a = new Array(); c = new Date(); a = document.cookie.split(';'); document.cookie=a[0]+"; expires="+c.toGMTString()+";" window.alert(document.cookie); ... <form> <input type=button value="Чтобы не хранить этот хлам вечно" onClick="change_cookies()"> </form> function asign() { document.cookie="n1=3"; window.alert(document.cookie); } ... <form> <input type=button value="Изменить n1" onClick="asign()"> </form> <form> <input type=button value="Показать Cookies" onClick="window.alert(window.document.cookie);"> </form> <style type="text/css"> div{ padding-bottom:5px; } </style> <script type="text/javascript"> function f(){ var namecom = document.getElementById('namecom'); var email = document.getElementById('email'); var site = document.getElementById('site'); document.cookie = 'namecom=' + encodeURIComponent(namecom.value) + '; max-age=' + (365*24*60*60) + '; path=/'; document.cookie = 'email=' + encodeURIComponent(email.value) + '; max-age=' + (365*24*60*60) + '; path=/'; document.cookie = 'site=' + encodeURIComponent(site.value) + '; max-age=' + (365*24*60*60) + '; path=/'; } function opencookie(par){ var allcookies = document.cookie; var pos = allcookies.indexOf(par); var dlina = par.length; if(pos !== -1){ var start = pos + dlina + 1; var end = allcookies.indexOf(';', start); if (end == -1) end = allcookies.length; var znachenie = allcookies.substring(start, end); znachenie = decodeURIComponent(znachenie); this.cooka = znachenie; } } function z(){ alert('Содержимое cookies' + document.cookie); if (document.cookie !== ''){ var namecomcooka = new opencookie('namecom'); alert(namecomcooka.cooka); var emailcooka = new opencookie('email'); alert(emailcooka.cooka); var sitecooka = new opencookie('site'); alert(sitecooka.cooka); var namecom = document.getElementById('namecom'); var email = document.getElementById('email'); var site = document.getElementById('site'); namecom.value = namecomcooka.cooka; email.value = emailcooka.cooka; site.value = sitecooka.cooka; } } </script> </head> <body onload="z()"> <p>Форма с полями ввода:</p> <div><input type="text" id="namecom"/> Имя</div> <div><input type="text" id="email"/> E-mail</div> <div><input type="text" id="site"/> Сайт</div> <div><input type="button" value="Отправить" onclick="f()"/></div> </body> document.querySelector or document.querySelectorAll ООП Объекты extending Array.prototype.longestElement = function() { var maxLength = 0; for (var i=0; i < this.length; i++) { if (this[i].toString().length > maxLength) maxLength = this[i].toString().length; } return maxLength; } inheritancefunction Rectangle(w,h) { this.width = w; this.height = h; } Rectangle.prototype.area = function() { return (this.width * this.height); } Rectangle.prototype.toString = function() { return "Rectangle of width: " + this.width + " and height: " + this.height; } Rectangle.prototype.valueOf = function() { return this.area(); } Rectangle.prototype.equals = function(oRect) { return (this.width == oRect.width && this.height == oRect.height); } Rectangle.prototype.compareTo = function(oRect) { return (this.area() - oRect.area()); } function DepthRectangle(w,h,d) { Rectangle.call(this,w,h); this.depth = d; } DepthRectangle.prototype = new Rectangle(); DepthRectangle.prototype.constructor = DepthRectangle; DepthRectangle.prototype.volume = function() { return (this.area() * this.depth); } DepthRectangle.prototype.toString = function() { return "DepthRectangle with width: " + this.width + " & height: " + this.height + " & depth: " + this.depth; } var myRect = new Rectangle(5,6); var myDeepRect = new DepthRectangle(7,8,9); alert(myDeepRect.volume()); alert(myDeepRect.area()); alert(myRect instanceof DepthRectangle); function Bird(name) { this.name = name; } Bird.prototype.flighted = true; // Default for all Birds Bird.prototype.isFlighted = function () { return this.flighted }; Bird.prototype.getName = function () { return this.name }; function Chicken(name) { // Chain the constructors Chicken.superclass.constructor.call(this, name); } приятно знать function include(file,scriptStack) { var script = document.createElement('script'); script.src = file; script.type = 'text/javascript'; if(scriptStack == 'async' && elemHasAttribute('script','async')) script.async = true; else if(scriptStack == 'defer') script.defer = true; document.getElementsByTagName('head')[0].appendChild(script); debuggStack({'msg':'script.js(47): include '+file}); }; //Include js file with callback function function includeWithCallBack(file, callback) { var script = document.createElement('script'); script.src = file; script.type = 'text/javascript'; document.getElementsByTagName('head')[0].appendChild(script); script.onreadystatechange = function() { if(script.readyState == "complete" || script.readyState=="loaded") { script.onreadystatechange = false; callback; } else { script.onload = function() { callback; }; } }; }; function elemHasAttribute(elementName,attribute){ var element = document.createElement(elementName); return attribute in element; }; HTML5 feature detection Include script Cheack attribute function hasColorSupport(){ input = document.createElement("input" ); input.setAttribute("type" , "color" ); var hasColorType = (input.type !== "text" ); // handle Safari/Chrome partial implementation if(hasColorType){ var testString = "foo" ; input.value=testString; hasColorType = (input.value != testString); } return(hasColorType); }` function hasAutofocus() { var element = document.createElement('input' ); return 'autofocus' in element; } $(function(){ if(!hasAutofocus()){ $('input[autofocus=true]' ).focus(); } }); var frag = document.createDocumentFragment(); local & Session storage $.fn.autosave = function(prefix){ var storage = localStorage; // or sessionStorage var $this = $(this); if(!prefix){ prefix = $this.attr('id'); } prefix += ">"; // Separate prefix from input name; function save(){ console.log('save') $this.find('input:not(:password, :submit)').each(function(index, element){ var key = prefix + element.name; storage.setItem(key, $(element).val()); }) }; function restore(){ var i, key, value, name; for(i=0; i < storage.length; i++){ key = storage.key(i); if(0 === key.indexOf(prefix)){ value = storage.getItem(key); name = key.replace(prefix, ''); $this.find('[name='+name+']').val(value); } } }; function clear(e){ var keys = [], i, key; // Collect Keys; for(i=0; i < storage.length; i++){ key = storage.key(i); if(0 === key.indexOf(prefix)){ keys.push(key); } } // Remove Each Key for(i=0; i < keys.length; i++ ){ storage.removeItem(keys[i]); } }; $this.change(save); $this.submit(clear); restore(); console.log('DONE') $(document).ready(function() { if (window.localStorage) { var fromDb = localStorage.getItem("courses"); if (fromDb) { // Read the courses from local storage, into the global "courses" array. courses = JSON.parse(fromDb); } else { // Store the global "courses" array into local storage. storeCourses(); } } }); // Stores the global "courses" array into local storage. function storeCourses() { if (window.localStorage) { localStorage.setItem("courses", JSON.stringify(courses)); } } HTML5 REF Events style origin Elems Elems Attr DOM Exeptions Categories ©Trybynenko Andrii