按钮、提示和警报

Button, Prompt, and Alert

我的 html 中有一个按钮元素,如下所示:

<button id = "buttonOne" type = "button" onclick = "buttonOne()">
Click Me!
</button>

我的 js 文件中有一个函数,如下所示:

function buttonOne() {

    var input = prompt("Please enter your first name followed by a comma and then 
    your age (ex. Mikey, 12):");

    var name = input.substring(0, indexOf(","));

    alert(name);
}

我想做的是仅提醒从提示中检索到的名称。但是,我的按钮似乎不再激活提示了。

function buttonOne() {
  var input = prompt("Please enter your first name followed by a comma and then your age (ex. Mikey, 12):");
  var name = input.substring(0, input.indexOf(","));
  if(name){
    alert(name);
  }else{
    alert('Uh huh.. please enter in correct format');
  }
}
<button id="buttonOne" type="button"onclick="buttonOne()">
  Click Me!
</button>

您需要使用以下方法获取名称。

var name = input.substring(0, input.indexOf(","));

首先检查逗号。如果没有找到,显示一条错误消息。

   var commaIdx = input.indexOf(",");
   if (commaIdx == -1) {
     alert("Input Invalid");
   } else {
     var name = input.substring(0, commaIdx);
     alert(name);
   }

试试这个

[1] 从 prompt

得到 input

[2]有效input

[3] 用逗号分隔 NameAge

function buttonOne() {
    var input = prompt("Please enter your first name followed by a comma and then your age (ex. Mikey, 12):");
    
    if (input.indexOf(",") == -1) {
        alert("Input Invalid");
    } else {
     var info = input.split(',');
        alert("Name:" + info[0] + ", Age:" + info[1]);
    }
}
<button id = "buttonOne" type = "button" onclick="buttonOne();">
Click Me!
</button>