javascript - 检查对提示的响应是否为某个字符串
问题描述
我想检查用户是否输入了一个字符串并验证输入的字符串是对还是错。
到目前为止,我已经通过使用 prompt() 来使用 JavaScript。
我成功显示了提示消息,当我输入任何名称时,它什么都不显示。我无法获得所需的输出。
function myFunction() {
var myText = prompt("Hello World");
var response;
if (myText.search(charIn) > 0) {
response = "Yes, that letter is in the string";
} else {
response = "No good, that letter is NOT in the string";
}
document.getElementById("demo").innerHTML = response;
}
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
解决方案
我相信您需要将提示值分配给变量charIn
并将Hello World分配给myText
.
另外最好用includes()
。
工作代码示例:
function myFunction() {
var myText = 'Hello World'
var charIn = prompt();
var response;
if (myText.includes(charIn)){
response = "Yes, that letter is in the string";
}else{
response = "No good, that letter is NOT in the string";
}
document.getElementById("demo").innerHTML = response;
}
myFunction();
<span id="demo"></span>
推荐阅读
- python - 如何通过 ForeignKey 访问模型的 __str__ 方法?
- angular - 使用 TypeScript 而不是 JavaScript 配置 Angular DataTable Renderer
- node.js - 如何在 NodeJS 中加载模块之前获取和使用 Secret Manager 值?
- c# - 数据库 ASP.NET MVC 5 中的对象持久性问题
- c# - asp中的票龄
- graphql - 错误:字段 createdAt:在任何模式中都找不到类型 DateTime
- angular - 如何在表格中正确编码/标记表单控件
- ionic3 - Azure Active Directory 的应用程序配置错误
- ruby-on-rails - rails select_month 默认值或参数
- parallel-processing - Rxjava2如何让flatMap按调用顺序发射项目?