ユーザーが現在そのページにいる場合、ボタンを無効にしようとしています。より効率的な方法があることはわかっていますが、if、else を練習しています。
問題は、リンクをクリックすることができ、リンクをクリックして同じページにいると、両方がページを更新することです。私のコード:
$("#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
は、次のような本格的な 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';
}
});
参照:-
2 つの特定の URL だけでボタンを無効にするif
場合は、 によって提供される条件でフルパスを使用しますconsole.log(window.location.href);
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加