【问题标题】:How to prevent a user from being redirected to a link in JavaScript?如何防止用户被重定向到 JavaScript 中的链接?
【发布时间】:2019-03-23 02:25:01
【问题描述】:

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。当用户单击链接时,我希望弹出一条带有消息的警报,但我不希望链接将他们重定向到该页面。当我使用开发人员工具在 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>

`

【问题讨论】:

  • 您正在尝试重新分配 jQuery 的 $ - 不要这样做。还要确保您使用的是 jQuery:<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

标签: javascript jquery html function


【解决方案1】:

你需要使用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() {
...

【讨论】:

  • 即使我使用这个方法,它也会给我同样的错误信息 Uncaught TypeError: cannot read property 'ready' of null.
  • 您是否在 html 页面底部添加了<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
  • 另外,请确保删除 var $ = function(id) { 函数
【解决方案2】:

您的问题是您将 jQuery 的 $ 函数重新定义为您自己的自定义函数。不要这样做!它完全使 jQuery 无效(您必须使用详细的 jQuery 表单)。您也可以使用preventDefault 来防止超链接更改您的页面。

$(document).ready(function () {
    "use strict";
    $('redirect').click(function(e) {
        e.preventDefault();
        window.alert('you clicked the link');
    }); 
});

还要确保您有 jQuery - 将其放在页面顶部:

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

【讨论】:

    【解决方案3】:
    var $ = function (id) {
        "use strict";
        return document.getElementById(id);
    };
    

    如果您使用$ 作为您的 jQuery 包装器,那么上面的代码会覆盖该变量。这意味着它不再是 jQuery,而是您设置的自定义函数。尝试更改上面的函数或变量的名称。

    【讨论】:

      猜你喜欢
      • 2014-03-10
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 2013-02-23
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      相关资源
      最近更新 更多