如果链接以 # 开头,如何禁用 JavaScript 点击功能?
javascriptweb developmentobject oriented programming更新于 2025/8/16 19:56:17
为此,请在 JavaScript 中使用 PreventDefault()。以下是 JavaScript 代码 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<a href="urlLink">Press Me to see logs</a>
<a href="urlLink">Press Me to see logs in console</a>
<a href="#">Nothing will happen</a>
<script>
$(function(){
$("a:not([href='#'])").click(function(event){
event.preventDefault();
console.log("You have pressed me!!!!!");
});
});
</script>
</body>
</html>
要运行上述程序,请将文件名保存为 anyName.html(index.html),然后右键单击该文件。在 VS 代码编辑器中选择选项 使用实时服务器打开。
输出

如果您单击两个链接 Press Me to see logs 和 Press Me to see logs in console,那么您将获得控制台输出。但是,如果您点击链接什么都不会发生,那么它不会打印任何内容 −

上面,我按下了按我来查看日志以显示输出。
如果您点击链接什么都不会发生,那么它不会打印任何内容,如下面的输出所示 −

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

