【问题标题】:Button, Prompt, and Alert按钮、提示和警报
【发布时间】:2018-07-26 19:23:40
【问题描述】:

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

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

【问题讨论】:

  • 更正:我确实收到了提示,因为我修复了子字符串中应该是逗号的句点,但我的警报没有出现
  • 在 input.substring(0.indexOf... 你有一个点 (.) 而不是逗号
  • 使用您的开发者控制台。我确定其中有错误。

标签: javascript substring alert prompt


【解决方案1】:

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(","));

【讨论】:

  • 你真的应该检查 input.indexOf(",") 没有返回 -1
【解决方案2】:

首先检查逗号。如果未找到,则显示错误消息。

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

【讨论】:

  • 我什至没有收到输入无效的警报,但是我尝试在此站点上的 code sn-p 选项上运行代码并且它有效...我的问题是什么?
  • @TommySon 如果你在输入中没有逗号,你应该得到这个
【解决方案3】:

试试这个

[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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 2011-11-15
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2015-07-15
    相关资源
    最近更新 更多