var $ = function (id) {
"use strict";
return document.getElementById(id);
};
$(document).ready(function () {
"use strict";
$('redirect').click(function () {
window.alert('you clicked the link');
return false;
});
});
<a href="http://www.google.com" id="redirect">Visit Goggle</a>
我有一个 HTML 格式的链接,我想在其余代码中使用 JavaScript 和 Jquery。当用户单击该链接时,我希望弹出一 strip 有消息的警报,但我不希望该链接将他们重定向到该页面。当我使用开发人员工具在 Chrome 中查看我的代码时,我收到一条错误消息,内容为“Uncaught TypeError: cannot read property of 'ready' of null”。为什么 ready 属性变为 null,我该如何解决?
var $ = function (id) {
"use strict";
return document.getElementById(id);
};
$(document).ready (function () {
"use strict";
$('redirect').click(function () {
window.alert('you clicked the link');
return false;
});
});
<a href="http://www.google.com" id="redirect">Visit Goggle</a>
`
最佳答案
你需要使用e.preventDefault()
,像这样:
$(document).ready(function () {
$('#redirect').click(function (e) {
e.preventDefault();
window.alert('you clicked the link');
});
});
此外,如果您需要按类(使用 jQuery)引用元素:
$('.someClass').on('click', function() {
...
如果你想访问它们 按编号:
$('#someId').on('click', function() {
...
关于javascript - 如何防止用户被重定向到 JavaScript 中的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55310022/