JavaScript 基础
Document
运算符
深入数据和类型
函数进阶
原型、继承
类
浏览器存储
Web API
事件
错误处理
异步编程
网络请求
模块
练习
实例
工具与规范
软件架构模式
设计模式
浏览器默认行为
浏览器会对事件的发生有着自己的默认处理,比如输入文本,点击超链接等。如果要禁止浏览器的默认行为,可以执行 event.preventDefault()
。
<input id="input" type="text" placeholder="无法输入的输入框" />
<script>
input.onkeydown = function (event) {
event.preventDefault() // 阻止默认浏览器行为
}
</script>
$$demo
<input id="input" type="text" placeholder="无法输入的输入框" /> <script> input.onkeydown = function (event) { event.preventDefault() // 阻止默认浏览器行为 } </script>
$$
以下是一个无法跳转的超链接。
<a id="link" href="https://3yya.com/">无法跳转的链接</a>
<script>
link.onclick = function (event) {
event.preventDefault() // 阻止默认浏览器行为
}
</script>
$$demo
<a id="link" href="https://3yya.com/">无法跳转的链接</a> <script> link.onclick = function (event) { event.preventDefault() // 阻止默认浏览器行为 } </script>
$$
练习
- 非三眼鸭的网站可能有病毒,用户点击跳转前确认一下。
<a href="https://3yya.com/" target="_blank">三眼鸭官网</a>
<a href="https://3yya.com/courseware" target="_blank">三眼鸭教材</a>
<a href="https://baidu.com/" target="_blank">百度</a>
<a href="https://www.bilibili.com/" target="_blank">bilibili</a>
<script>
// 补充 JavaScript 部分
</script>
$$demo
<a href="https://3yya.com/" target="_blank">三眼鸭官网</a> <a href="https://3yya.com/courseware" target="_blank">三眼鸭教材</a> <a href="https://baidu.com/" target="_blank">百度</a> <a href="https://www.bilibili.com/" target="_blank">bilibili</a> <script> document.querySelectorAll("a").forEach(function (element) { if (element.href.startsWith("https://3yya.com/")) { // 是三眼鸭的网站 return }
element.addEventListener("click", function (event) {
if (confirm(`确认打开链接: ${this.href} 吗?`)) {
// 确认打开
return
}
// 禁止跳转
event.preventDefault()
})
})
</script> $$
$$answer
<a href="https://3yya.com/" target="_blank">三眼鸭官网</a>
<a href="https://3yya.com/courseware" target="_blank">三眼鸭教材</a>
<a href="https://baidu.com/" target="_blank">百度</a>
<a href="https://www.bilibili.com/" target="_blank">bilibili</a>
<script>
document.querySelectorAll("a").forEach(function (element) {
if (element.href.startsWith("https://3yya.com/")) {
// 是三眼鸭的网站
return
}
element.addEventListener("click", function (event) {
if (confirm(`确认打开链接: ${this.href} 吗?`)) {
// 确认打开
return
}
// 禁止跳转
event.preventDefault()
})
})
</script>
$$