My:JS — различия между версиями

Материал из synset
Перейти к: навигация, поиск
(→‎Ссылки)
(→‎Примеры)
Строка 69: Строка 69:
 
== Примеры ==
 
== Примеры ==
  
 +
=== Проверка поля формы ===
 +
 +
This  script will check to see if there is any text in the text field "myText". The argument that getElementById requires is the id of the HTML element you wish to utilize.
 +
<pre class="brush:js; gutter: false;">
 
<script type="text/javascript">
 
<script type="text/javascript">
 
function notEmpty(){
 
function notEmpty(){
Строка 80: Строка 84:
 
<input type='text' id='myText' />
 
<input type='text' id='myText' />
 
<input type='button' onclick='notEmpty()' value='Form Checker' />
 
<input type='button' onclick='notEmpty()' value='Form Checker' />
 +
</pre>
  
 
== Ссылки ==
 
== Ссылки ==

Версия 06:03, 15 июля 2011

Введение

Подключение к html-файлу файла со скриптом происходит в разделе заголовка:

 
<head>
    <script type="text/javascript" src="script.js"></script>
</head>

Там же можно размещать непосредственно скрипт:

 
<head>
   <script language="javascript">
      document.write("Моя первая страница.");
    </script>
</head>

Эта программа, используя объект document (текущий в браузере) и его метод write пишет на экране текст. Данный сценарий выполняется сразу при открытии документа. В этом же скрипте могут находится функции, которые вызываются при возникновении тех или иных событий, например, при клике на некоторой группе:

 
<div onClick="showMessage();"></div>

Если в head (или подключаемом файле) описана функция:

 
function showMessage()
{
  alert ("Вы щелкнули по div-у");
}

при клике на тексте выскочит окошко.

Работа с формами

Форма перемножающая два числа:

 
<form name="form_add">
    <input type="text" name="t1" size="10"> * <input type="text" name="t2" size="10"> 
    <input type="button" name="button" value="=" onClick="Mult();">
    <input type="text" name="res" size="10">
</form>

Скрипт:

 
function Mult()
{
   var a= document.form_add.t1.value;
   var b= document.form_add.t2.value;
   document.form_add.res.value=a*b;
}

Но более удобно через кнопку передать имя формы:

 
<input type="button" name="button" value="=" onClick="Mult(form_add);">

и функцию написать так:

 
function Mult()
{
   obj.res.value=obj.t1.value * obj.t2.value;
}

События

  • onClick
  • onMouseUp

Примеры

Проверка поля формы

This script will check to see if there is any text in the text field "myText". The argument that getElementById requires is the id of the HTML element you wish to utilize.

 
<script type="text/javascript">
function notEmpty(){
	var myTextField = document.getElementById('myText');
	if(myTextField.value != "")
		alert("You entered: " + myTextField.value)
	else
		alert("Would you please enter some text?")		
}
</script>
<input type='text' id='myText' />
<input type='button' onclick='notEmpty()' value='Form Checker' />

Ссылки

См.также