javascript:void(0)
是一个常见的 HTML 属性值,用于阻止链接的默认行为。具体来说,当用户点击带有 javascript:void(0)
的链接时,浏览器不会导航到新的页面,也不会执行任何 JavaScript 代码。这个表达式的意思是执行一个空的 JavaScript 函数,从而防止任何操作。
javascript:void(0);
。有时开发者可能会遇到点击带有javascript:void(0)
的链接后页面仍然发生跳转的情况。
void(0)
之前如果有JavaScript错误,可能会阻止预期的行为。event.stopPropagation()
来阻止事件继续传播到父元素。event.stopPropagation()
来阻止事件继续传播到父元素。以下是一个简单的例子,展示了如何使用javascript:void(0)
并结合JavaScript来打开一个模态框:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Void Example</title>
<style>
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<button id="openModalBtn" onclick="openModal()">Open Modal</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal()">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<script>
function openModal() {
document.getElementById("myModal").style.display = "block";
}
function closeModal() {
document.getElementById("myModal").style.display = "none";
}
</script>
</body>
</html>
在这个例子中,点击按钮会打开一个模态框,而不是导航到新页面。
领取专属 10元无门槛券
手把手带您无忧上云