2014-11-07 2 views
-3

Я новичок в JavaScript, и мне интересно, что это означает на простом английском языке.Я не понимаю этот код от javascript

<!DOCTYPE html> 
<html> 
<body> 

<p>Please input a number between 5 and 10:</p> 

<input id="demo" type="text"> 
<button type="button" onclick="myFunction()">Test Input</button> 

<p id="message"></p> 

<script> 
function myFunction() { 
    *** var message, x; *** 
    *** message = document.getElementById("message"); *** 
    *** message.innerHTML = ""; *** 
    x = document.getElementById("demo").value; 
    try { 
     if(x == "") throw "is Empty"; 
     if(isNaN(x)) throw "not a number"; 
     if(x > 10) throw "too high"; 
     if(x < 5) throw "too low"; 
    } 
    catch(err) { 
     message.innerHTML = "Input " + err; 
    } 
    finally { 
     document.getElementById("demo").value = ""; 
    } 
} 
</script> 

</body> 
</html> 

Я не понимаю, какая часть между ***. почему они используют обмен сообщениями и помещают его в обмен сообщениями? пожалуйста, помогите и определите любые программные слова, которые чрезвычайно известный человек не понимает.

чем вы.

ответ

2

var message, x;

Объявляются две переменные message и x, которые в настоящее время не определены.

message = document.getElementById("message");

Теперь мы относим узел DOM, который имеет идентификатор «сообщения» переменной message

message.innerHTML = "";

теперь опустошить все, что может быть внутри контейнера DOM.

0
var message, x; 

Это говорит о том, что переменные message и x будут использоваться в пределах этого объема. То есть мы хотим переменные message и x в функции myFunction(), а не переменные message и x, которые могут быть определены за ее пределами.

message = document.getElementById("message"); 

Переменная message будет содержать фактический элемент с идентификатором message на этой странице. Отсюда вперед мы можем вызывать методы и задавать свойства по переменной message, так как это элемент на самой странице.

message.innerHTML = ""; 

Это способ очистить содержимое message. По умолчанию это пустое. В коде сообщение может быть добавлено, если есть ошибка. Человек, который написал это, решил сначала удалить любое предыдущее сообщение об ошибке, чтобы, если бы эта функция преуспела, сообщение об ошибке не было показано.

1

Вот строка за строкой пробоя:

function myFunction() { 
    // declare variables message and x with no value or type 
    var message, x; 

    // set message to the DOM element with the id of "message" 
    message = document.getElementById("message"); 

    // set the inner HTML (the content inside the div) of message to be an empty string 
    message.innerHTML = ""; 

    // set x to be the value of the DOM element with the id of "demo" 
    x = document.getElementById("demo").value; 

    // try some cases 
    try { 
     // if the x's value is an empty string, return a descriptive string 
     if(x == "") throw "is Empty"; 
     // if the x's value is a not a number, return a descriptive string 
     if(isNaN(x)) throw "not a number"; 
     // if the x's value is greater than 10, return a descriptive string 
     if(x > 10) throw "too high"; 
     // if the x's value is less than 5, return a descriptive string 
     if(x < 5) throw "too low"; 
    } 
    // catch an error if none of the cases match 
    catch(err) { 
     // display an error message in the message DOM element 
     message.innerHTML = "Input " + err; 
    } 
    // finally clause executes after try and catch execute, but before the statements following the try statement 
    finally { 
     // set the value of the demo DOM element to be an empty string 
     document.getElementById("demo").value = ""; 
    } 
} 
+0

+1 за расходы слишком много времени на этот ответ. – AlienWebguy

+0

им все еще интересно, как он был смущен строк, которые он выделил, и остальной код – elzi

0
function myFunction() { 
    // I am going to use the variables message and x in function 
    // but they don´t have a value yet 
    var message, x; 
    // assign message to be the element with id="message" 
    message = document.getElementById("message"); 
    // remove all text from message 
    message.innerHTML = ""; 
+0

Я просто понял, что он добавил звездочки сам, чтобы выделить код. Чувство очень застенчивое. – max

Смежные вопросы