1

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

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

$("#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';
    };
});

4

2 回答 2

0

验证 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();
            }
于 2017-03-16T05:00:29.243 回答
0

实际上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() 功能

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

于 2017-03-16T05:03:07.373 回答