JavaScript初級教程(第二課)第4/7頁
更新時間:2007年04月05日 00:00:00 作者:
"if"子句的應用可以使得程序根據(jù)用戶輸入的值作出不同的反應。例如你可以寫一段程序使得它對你與對其他人反應不同。這里是它的基本格式:
if (some condition is true)
{
do something;
do something;
do something;
}
本結構的重要部分:
以單詞 "if"開始 (if 必須小寫).
圓括弧中是條件:非真即偽。
如果條件為真的話執(zhí)行花括弧中的語句。
記?。嚎崭袷俏ㄒ槐3殖绦蚩勺x性的東西。當然你可以將整個if語句寫在一行中,但它讀起來就費勁了。
這里是一個if子句的例子。
<script language="JavaScript">
<!-- hide me
var monkey_love = prompt("你喜歡網(wǎng)猴嗎?","敲入是或否。");
if (monkey_love == "是")
{
alert("謝謝!很高興您能來這兒!請往下讀吧!");
}
// end hide -->
</script>
如果你在即時對話框中鍵入yes,你將收到一個親切的問候。若敲入別的則沒有。
這里是該語句的核心:
var monkey_love = prompt("你喜歡網(wǎng)猴嗎?","敲入是或否。");
if (monkey_love == "是")
{
alert("謝謝!很高興您能來這兒!請往下讀吧!");
}
第一行你見過。它喚起一個對話框并將用戶的反饋調入變量monkey_love中。但第二行就有些不同:它有個條件,即如果變量monkey_love等于值"是" ,則運行花括號中的語句。若它等于其他值,則不運行。
注意該條件中的兩個等于標記,這是人們容易搞混的地方之一。如果你只用一個標記,實際上是告訴JavaScript測試是否monkey_love等于 "是"。幸運的是,多數(shù)瀏覽器在你運行這些語句時會識別這些錯誤并警告你。但最好現(xiàn)在開始就注意別犯這種錯誤。
其他重要的條件是:
(variable_1 > variable_2) is true if variable_1 is greater than variable_2
(variable_1 < variable_2) is true if variable_1 is less than variable_2
(variable_2 <= variable_2) is true if variable_1 is less than or equal to variable_2
(variable_1 != variable_2) is true if variable_1 does not equal variable_2
有兩個方法可使你的條件更合理:
在運行花括號中的語句前如果你想要兩件事為“是”,可這樣做:
if ((variable_1 > 18) && (variable_1 < 21))
{
document.writeln("variable_1 can vote, but can't drink.");
}
注意這里的兩個“&&”在JavaScript中這是“與”的意思。也注意整個子句有兩個部分,&&須在圓括號中。
若想兩件事之一為真,這樣做:
if ((variable_1 == "bananas") || (variable_1 == "JavaScript"))
{
document.writeln("The monkey is happy because it has " + variable_1);
}
回到if練習中來!
<script language="JavaScript">
var color = prompt("您喜歡哪種顏色,red還是blue?","");
var adjective;
var fontcolor;
if (color == "red") {
adjective = "活潑。";
fontcolor="red";
} else if (color == "blue") {
adjective = "酷。";
fontcolor="blue";
} else {
adjective = "困惑。";
fontcolor="black";
}
var sentence = "您喜歡" + fontcolor + "? 網(wǎng)猴認為您很" + adjective + "<p>";
document.writeln(sentence.fontcolor(fontcolor));
</script>
相關文章
在JavaScript中用getMinutes()方法返回指定的分時刻
這篇文章主要介紹了在JavaScript中用getMinutes()方法返回指定的分時刻,是JS入門學習中的基礎知識,需要的朋友可以參考下2015-06-06javascript scrollLeft,scrollWidth,clientWidth,offsetWidth 完全
javascript scrollLeft,scrollWidth,clientWidth,offsetWidth 完全詳解,實例修正版。2009-07-07