2016-12-29 2 views
0

Я пишу скрипт для изменения того, какой элемент виден на основе строки в хеше. Сценарий перейдет на страницу блога, где пользователь может фильтровать записи в блогах по категориям. Когда пользователь фильтрует определенную категорию, эта категория добавляется к URL-адресу в виде хэш-ссылки.Если url hash не содержит никакой строки, выполните функцию

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-адрес заканчивается одним хэшем?

У меня есть кодофф, настроенный (http://codepen.io/ben393/pen/GNVqRX), чтобы показать это в действии.

+0

не является ответ, но вы можете использовать 'window.location.hash', который даст хэш в форме« #hospitality ». Затем вы должны создать оператор switch (или если еще) с точными совпадениями. Использование indexOf, как вы сейчас делаете, может давать ложные срабатывания. –

ответ

1

Не уверен, почему вы используете эти переменные фраг, он никогда не меняется.

Вы можете сделать следующее

if(window.location.hash.length < 2) { ..... }

Кроме того, если ничто не мешает вам, то вы можете использовать onhashchange событие вместо непрерывной проверки через setInterval

$(window).bind('hashchange', hashClassChange); 
0

Вы можете проверить, что последний символ # или нет.

var lastChar = location.pathname.substr(location.pathname.length - 1); 
if(lastChar == '#') 
//Your default textbox show hide logic goes here 
+0

Я думаю, что я правильно сменил сценарий, чтобы отразить ваше предложение [link] (http://codepen.io/ben393/pen/MbNbod), но мой скрипт не работает. Возможно, моя логика или расположение переменных плохие, потому что я новичок. – Ben393

0

Не могли бы вы попробовать с ниже код:

//If the url hash does not contain any string, show the default box 
else if (frag.length < 1 || (frag.length > 1 && frag[1].length == 0)) { 
    //if we don't have # in URL then frag will have only single 0th index 
    //if we have # in URL but nothing after that then its length will be zero 
    $('#default').addClass("active"); 
    $('#box1').removeClass("active"); 
    $('#box2').removeClass("active"); 
    $('#box3').removeClass("active"); 
    $('#box3').removeClass("active"); 
} 
+0

Я обновил свой [codepen] (http://codepen.io/ben393/pen/Vmomrb), чтобы включить ваши изменения, я не могу заставить это работать. – Ben393

1

Проблема в том, что при нажатии на кнопку по умолчанию window.location.hash будет empty string поэтому он не будет идти в первый, если в результате последнего нажатия одной будут видны.

удалите if (window.location.hash) {} деталь и он будет работать так, как вы ожидаете.

var frag; 
 
frag = window.location.href.split("#"); 
 
var hashClassChange = function() { 
 
\t 
 
    if (window.location.hash.indexOf('commercial') == 1) { 
 
     $('#box1').addClass("active"); 
 
     $('#default').removeClass("active"); 
 
     $('#box2').removeClass("active"); 
 
     $('#box3').removeClass("active"); 
 
     $('#box4').removeClass("active"); 
 
    } 
 
    else if (window.location.hash.indexOf('hospitality') == 1) { 
 
     $('#box2').addClass("active"); 
 
     $('#default').removeClass("active");; 
 
     $('#box1').removeClass("active"); 
 
     $('#box3').removeClass("active"); 
 
     $('#box4').removeClass("active"); 
 
    } 
 

 
    else if (window.location.hash.indexOf('municipal-institutional') == 1) { 
 
     $('#box3').addClass("active"); 
 
     $('#default').removeClass("active"); 
 
     $('#box1').removeClass("active"); 
 
     $('#box2').removeClass("active"); 
 
     $('#box4').removeClass("active"); 
 
    } 
 
    else if (window.location.hash.indexOf('residential') == 1) { 
 
     $('#box4').addClass("active"); 
 
     $('#default').removeClass("active"); 
 
     $('#box1').removeClass("active"); 
 
     $('#box2').removeClass("active"); 
 
     $('#box3').removeClass("active"); 
 
    } 
 
    else if (typeof frag[1] == 'undefined' || !frag[1].length) { 
 
     $('#default').addClass("active"); 
 
     $('#box1').removeClass("active"); 
 
     $('#box2').removeClass("active"); 
 
     $('#box3').removeClass("active"); 
 
     $('#box3').removeClass("active"); 
 
    } 
 
}; 
 

 
setInterval(hashClassChange, 500);
body{ 
 
    font-family:sans-serif; 
 
} 
 
#default{ 
 
    background:red; 
 
} 
 
#box1{ 
 
    background:orange; 
 
} 
 
#box2{ 
 
    background:yellow; 
 
} 
 
#box3{ 
 
    background:green; 
 
} 
 
#box4{ 
 
    background:lightblue; 
 
} 
 
li { 
 
    display: inline-block; 
 
    width: 400px; 
 
    padding: 10px; 
 
    position: absolute; 
 
    opacity: 0; 
 
    transition: opacity 1s; 
 
} 
 
li.active{ 
 
    opacity: 1; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
Links to filter posts: 
 
<a href="#">no category (show all posts)</a> | 
 
<a href="#commercial">Commercial</a> | 
 
<a href="#hospitality">Hospitality</a> | 
 
<a href="#municipal-institutional">Municipal/Institutional</a> | 
 
<a href="#residential">Residential</a> 
 

 
<ul> 
 
    <li id="default" class="active"><b>Default text</b> Quisque posuere augue eu vulputate vestibulum. Mauris lacinia diam sit amet magna vulputate sodales et vel magna. Integer eros diam, faucibus nec mi sit amet, suscipit ornare massa. Praesent convallis ut lorem fringilla fringilla. Pellentesque sed nisi sapien. Maecenas sit amet placerat augue. Nullam auctor ligula risus, et laoreet nisl varius ac. Donec euismod erat neque, in viverra sapien luctus eget.</li> 
 
    <li id="box1"><b>Commercial text</b> Nulla justo quam, sagittis in turpis a, rutrum dapibus tellus. Sed porttitor massa nec urna rutrum finibus. In sit amet sagittis orci. Proin ligula quam, tempus eget ligula nec, gravida venenatis tellus. Quisque vitae nisl a ipsum semper finibus. Proin vehicula molestie arcu, nec facilisis justo tempus id. Morbi lectus dui, luctus non tellus ac, varius aliquam dui. Morbi commodo nulla eget luctus ullamcorper. Nulla facilisi. Fusce dapibus vestibulum sapien, ut laoreet libero pharetra in.</li> 
 
    <li id="box2"><b>Hospitality text</b> Sed eget nunc lobortis, varius felis ut, scelerisque tortor. Maecenas vitae nunc leo. Mauris non facilisis risus, vel tincidunt enim. Donec pharetra nisi id suscipit consectetur. Integer lacinia in eros at tincidunt. Praesent et enim sem. Sed in viverra erat, vitae tempus felis. Vestibulum id sodales leo.</li> 
 
    <li id="box3"><b>Municipal/Institutional text</b> Maecenas rutrum diam nec sapien consectetur, a viverra enim commodo. Curabitur a eros risus. Quisque viverra elementum ipsum, sit amet commodo libero tristique non. Nullam blandit interdum dolor non vulputate. Morbi et lacus blandit, blandit ipsum non, mollis eros. Duis sit amet ex sed felis congue vestibulum. Aliquam ultrices viverra est, quis posuere est consectetur vel. Duis viverra magna sed dignissim semper. Pellentesque varius pretium justo, eleifend placerat lectus fringilla non.</li> 
 
    <li id="box4"><b>Residential text</b> Pellentesque dui enim, pulvinar et dignissim a, ultricies sed sapien. Mauris pulvinar ipsum a est feugiat euismod. Cras sed rutrum lorem. Aenean cursus a augue in laoreet. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse non luctus lacus, in dignissim diam. Quisque vitae ipsum ac eros cursus consectetur non id libero. Aenean mauris nisl, sagittis vitae nisi et, sagittis venenatis ligula. Donec libero odio, vulputate et lacinia quis, feugiat quis dui.</li> 
 
</ul>

Смежные вопросы