ハッシュの文字列に基づいて表示される要素を変更するスクリプトを作成しています。スクリプトは、ユーザーがカテゴリ別にブログ投稿をフィルタリングできるブログページに移動します。ユーザーが特定のカテゴリにフィルタすると、そのカテゴリがハッシュリンクの形でURLに追加されます。urlハッシュに文字列が含まれていない場合、関数
example.com/#categoryA
その時点で、フィルタリングされた投稿の各セットに対応するテキストボックスがポートフォリオの横に表示されます。ユーザーが投稿を濾過し、またはすべての投稿を表示するには、フィルタリングの記事から行くされていない場合は、このようなURLでの単一のハッシュがあります:この場合
example.com/#
は、私はにデフォルトのテキストボックスをしたいです示される。
私のスクリプト(下記)は、URLがちょうどハッシュで終わったときにデフォルトのテキストボックスを表示する以外はすべて行います。
var frag = window.location.href.split("#");
var hashClassChange = function() {
if (window.location.hash) {
//If the url hash contains commercial, show the commercial box, hide the last active box
if (window.location.hash.indexOf('commercial') == 1) {
$('#box1').addClass("active");
$('#default').removeClass("active");
$('#box2').removeClass("active");
$('#box3').removeClass("active");
$('#box4').removeClass("active");
}
//If the url hash contains hospitality, show the hospitality box, hide the last active box
else if (window.location.hash.indexOf('hospitality') == 1) {
$('#box2').addClass("active");
$('#default').removeClass("active");;
$('#box1').removeClass("active");
$('#box3').removeClass("active");
$('#box4').removeClass("active");
}
//If the url hash contains municipal-institutional, show the municipal/institutional box, hide the last active box
else if (window.location.hash.indexOf('municipal-institutional') == 1) {
$('#box3').addClass("active");
$('#default').removeClass("active");
$('#box1').removeClass("active");
$('#box2').removeClass("active");
$('#box4').removeClass("active");
}
//If the url hash contains residential, show the residential box, hide the last active box
else if (window.location.hash.indexOf('residential') == 1) {
$('#box4').addClass("active");
$('#default').removeClass("active");
$('#box1').removeClass("active");
$('#box2').removeClass("active");
$('#box3').removeClass("active");
}
//If the url hash does not contain any string, show the default box
else if (!frag[1].length) {
$('#default').addClass("active");
$('#box1').removeClass("active");
$('#box2').removeClass("active");
$('#box3').removeClass("active");
$('#box3').removeClass("active");
}
}
};
// repeats function every 500 milliseconds to check if the url hash has been changed
setInterval(hashClassChange, 500);
このスクリプトを修正して、URLが1つのハッシュで終わるときにデフォルトのテキストボックスが表示されるようにしますか?
私は実際にこれを示すためにコードセットを設定しました(http://codepen.io/ben393/pen/GNVqRX)。
ないを通じて代わりに連続チェックの
onhashchange
イベントを使用することができます。また、次のif(window.location.hash.length < 2) {
.....
}
を行うことができますあなたは '#hospitality 'の形式でハッシュを与える' window.location.hash'を使うことができます。次に、正確に一致するswitch文を作成する必要があります。あなたが今やっているようにindexOfを使うと誤検出が起こるかもしれません。 –