联系人保存结果不显示在Javascript中

Contact saving result is not showing in Javascript

本文关键字:Javascript 显示 保存 结果 联系人      更新时间:2023-09-26

我用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);
}

试试这个:

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,以便在您需要时可以使用它们使用。

这里的问题是变量的作用域。

试试这个:

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);
}

在JavaScript中,变量只能在特定的作用域中声明,对于声明它们的函数来说,可以是全局的,也可以是局部的。由于您在函数中声明了nam1, num1searc,因此它们在外部不可用。

看看你的错误控制台。通常你应该得到一个ReferenceError,至少在严格模式下。为了防止这种情况,在脚本的开头声明变量,并且不要在函数中重新声明