我的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);
}
我想做的是仅警告从提示中检索到的名称。但是,我的按钮似乎不再能激活提示。
答案 0 :(得分:2)
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(","));
答案 1 :(得分:0)
首先检查逗号。如果找不到,则显示错误消息。
var commaIdx = input.indexOf(",");
if (commaIdx == -1) {
alert("Input Invalid");
} else {
var name = input.substring(0, commaIdx);
alert(name);
}
答案 2 :(得分:0)
尝试一下
[1]从input
获得prompt
[2]有效的input
[3]用逗号Name
和Age
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>