【问题标题】:Why won't my jquery button disable为什么我的 jquery 按钮不能禁用
【发布时间】:2017-03-16 04:45:28
【问题描述】:

如果用户当前在该页面上,我正在尝试禁用按钮,我知道有更有效的方法,但我正在练习我的 if,否则。

问题是我仍然可以单击链接,如果我单击它们并且我在同一页面上,两者都会刷新页面。我的代码:

$("#homepage").on("click", function(event) {
    if (window.location.href === 'index.html') {
        $(this).attr('disabled', "disabled");
        $(this).attr('disabled', true);
        event.preventDefault();
    }else {
        window.location.href = 'index.html';
    };
});	
$("#aboutUs").on("click", function(event) {
    if (window.location.href === 'aboutus.html') {
        $(this).attr('disabled', "disabled");
        $(this).attr('disabled', true);
        event.preventDefault();
    }else {
        window.location.href = 'aboutus.html';
    };
});

【问题讨论】:

  • 记录window.location.href 是什么。永远不会是'index.html'
  • 检查console.log(window.location.href) 看看它的输出。我认为这是不同的东西,这就是为什么if 条件永远不会成功。
  • @AlivetoDie 在谷歌浏览器中,例如,加载时它将是file://C:\Users\admin\Desktop\MyWebsite\index.html。它就像在服务器上的https://www.example.com/index.html,或者在常规IP 地址142.153.31.22/index.html 上,并且永远不会只是“index.html”
  • 所以我是否正确地阅读了这一点,如果不先托管它以获取特定链接,就没有办法做到这一点?
  • @ChristianA 使用indexOf(),如下所示(在我的回答中)。检查并告诉我们是否有效?

标签: jquery button disable-link


【解决方案1】:

实际上window.location.href 会为您提供完整的 URL,例如:-

https://www.example.com/index.html

http://www.example.com/index.html

等等

这就是为什么您的 if 条件似乎永远不会成为真的原因。

使用indexOf(),如下所示:-

$("#homepage").on("click", function(event) {
    if (window.location.href.indexOf('index.html') >-1) {
            $(this).prop('disabled', true); // recomended to use `prop`
            event.preventDefault();
    }
    else {
        window.location.href = 'index.html';
    }
}); 
$("#aboutUs").on("click", function(event) {
    if (window.location.href.indexOf('aboutus.html')>-1) {
        $(this).prop('disabled', true);// recomended to use `prop`
        event.preventDefault();
    }
    else {
        window.location.href = 'aboutus.html';
    }
});

参考:-

indexOf() functionality

如果您只想禁用两个特定 URL 上的按钮,请在if 条件中使用由console.log(window.location.href); 提供的完整路径。

【讨论】:

  • 嗨,有没有一种简单的方法来解释 .indexOf('index.html') >-1 如何让它工作?或者你可以指点我的一些文件?
  • 我也发现了该文档,我只是没有以这种方式使用 .indexOf 链接和 > -1,请查看文档并希望我能理解它,谢谢
  • 嗨,如果我理解正确,它本质上是 -1 > -1 运行,但为什么不 -1 === -1?
  • no indexOf() 给出您正在搜索的字符串的位置,并且位置从 0 开始计数。所以它会像 0>-1
  • 我现在明白了,谢谢,我在控制台记录 aboutus.html,它给了我-1,因为我在索引页面上,所以我很困惑,为什么它工作
【解决方案2】:

验证window.location.href的值是什么

$("#homepage").on("click", function(event) {
alert( window.location.href);
});

而不是将这个值放在 if 条件中:

if (window.location.href === 'dummyrul/index.html') {
                $(this).attr('disabled', "disabled");
                $(this).attr('disabled', true);
                event.preventDefault();
            }

【讨论】:

  • @Christian A 试试这个
猜你喜欢
  • 2021-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 2019-05-06
  • 1970-01-01
  • 2021-09-27
相关资源
最近更新 更多