2013-05-03 89 views
0

我在JavaScript中編寫了電話號碼保護程序。一切正常,但是當我搜索一個名稱,或在搜索框中輸入數字正在顯示沒有結果:保存結果未顯示在Javascript中

function contact() { 
    var nam1=prompt("Please enter the name"); 
    var num1=prompt("please enter the phone number"); 
} 

contact(); 

function search() { 
    var searc= prompt("Please enter the name of your contact or phone number"); 
} 

search(); 

//search box 

if (searc == nam1) { 
    alert("The phone Number is , " + num1); 
} 

if (searc == num1) { 
    alert("The Contact Name is , " + nam1); 
} 

回答

1

這裏的問題是變量的範圍。

試試這個:

var nam1; 
var num1; 
var searc; 

function contact() { 

    nam1 = prompt("Please enter the name"); 
    num1 = prompt("please enter the phone number"); 

} 

contact(); 

function search() { 

    searc = prompt("Please enter the name of your contact or phone number"); 

} 

search(); 

//search box 

if (searc == nam1) { 

    alert("The phone Number is , " + num1); 

} 

if (searc == num1) { 

    alert("The Contact Name is , " + nam1); 

} 
+0

謝謝:)它的工作 – 2013-05-03 05:11:25

+0

@MISJHA複製我的答案? – 2013-05-03 05:20:25

+0

哈哈,一點都不! :)解決方案非常簡單! ;) – MISJHA 2013-05-03 05:22:07

2

試試這個:

var nam1=''; 
var num1=''; 
var searc=''; 

function contact() { 
    nam1=prompt("Please enter the name"); 
    num1=prompt("please enter the phone number"); 
} 
contact(); 
function search() { 
    searc= prompt("Please enter the name of your contact or phone number"); 
} 
search(); 
//search box 
if (searc == nam1) { 
    alert("The phone Number is , " + num1); 
} 
if (searc == num1) { 
    alert("The Contact Name is , " + nam1); 
} 

注:你應該define these variables globally讓他們在您使用 時可用。

+0

非常感謝......現在它的工作:) :) :) – 2013-05-03 05:10:53

0

在JavaScript變量只declared in a specific scope,無論是全球還是局部,他們已經宣佈的功能。由於您在函數中聲明瞭nam1,num1searc,因此他們不在外面。

看看你的錯誤控制檯。通常你應該得到一個ReferenceError,至少在嚴格模式下。爲了防止在你的腳本開頭聲明你的變量,並且不要在你的函數中重新聲明

+0

感謝您的幫助:) – 2013-05-03 05:12:03