2017-03-16 16 views
1

ユーザーが現在そのページにいる場合、ボタンを無効にしようとしていますが、より効率的な方法がありますが、if、elsesを練習しています。jqueryボタンが無効にならない理由

問題は、リンクをクリックすることができて、リンクをクリックするとページが更新され、同じページにあることです。私のコード:

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

+0

'window.location.href'が何であるかを記録します。決して '' index.html'' –

+1

'' console.log(window.location.href) 'をチェックして、その出力を確認してはいけません。私はそれが何か違うと思うので、それが 'if'条件が決して成功しない理由です。 –

+0

@AlivetoDie例えば、Google Chromeでは、読み込まれると 'file:// C:\ Users \ admin \ Desktop \ MyWebsite \ index.html'になります。サーバ上、または通常のIPアドレス '142.153.31.22/index.html'上では' https:// www.example.com/index.html'のようになり、決して** ** "index.htmlにはなりません" –

答えて

0

実際にwindow.location.hrefはあなたにフルハンドを与えるDの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

あなたは2つだけ、特定のURL'Sのボタンを無効にすることにより、提供あなたのif状態で完全なパスを使用したい場合console.log(window.location.href);

+0

こんにちは、それがどのように.indexOf( 'index.html')>働く?あなたが私の方法を指すことができるいくつかの文書ですか? –

+0

私はその文書も見つけました。このようにして.indexOfをリンクと> -1で使用していませんでした。ドキュメンテーションを見て、私の頭を包み込むことができれば幸いです。 –

+0

本質的に-1> -1を実行するが、なぜそうではない-1 === -1? –

0

何よりも

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

ようwindow.location.hrefの値であることが好きなら状態で、この値を入れていることを確認します。

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

@Christian Aこれを試してください – Faraz

関連する問題