【问题标题】:JavaScript input alerts userJavaScript 输入提醒用户
【发布时间】:2021-05-18 23:28:37
【问题描述】:

我有下面的代码,它当前的作用是如果用户键入 index.html,它将带入 index.html 等。但我想要的是,如果他们输入一个不存在的文件,它会提醒他们.例如,他们输入 hi.html 并且 hi.html 不存在,然后它会提醒他们说文件不存在。

代码:

let btn = document.querySelector('.ex');
let inputPath = document.querySelector('.path');

// redirect to chosen path
btn.addEventListener('click', function() {
  location.href = inputPath.value;
});
<input type='text' class='path' style="color: #222; background: white; padding: 5px; border-radius: 6px; border: none;">
<br><br><input type="submit" class="ex" value="Enter/submit" style="border-radius: 6px; font-size: 18px;display: inline-block; padding: 20px; border: none; background-color: royalblue; color: white;" />

【问题讨论】:

  • 如果用户选择了一个文件,那么你就知道它存在
  • 不,我不知道,因为如果文件不存在会发生什么,它会转到未找到的 404 页面。我希望它改为提醒用户

标签: javascript html css file input


【解决方案1】:

您必须检查您的可用文件以查看它是否存在。例如,

let files = ['index.html', 'hello.html']

然后,在您的事件侦听器中,您只允许有效文件重新分配location.href。对于其余的,您可以发送警报。例如,

if (files.some((file) => file == inputPath.value)) {
  location.href = inputPath.value
} else {
  alert('Not a valid path.')
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多