Громадное спасибо автору и комментаторам за статью, благодаря которой и стало возможным создание и внедрение скрипта независимого показа и скрытия множественных элементов на jQuery.
Если вы откроете Карту сайта, то сможете увидеть, как работает сниппет на множественных вложенных объектах...
При создании скрипта, прежде всего стояла цель, сделать переносимый и легко внедряемый код.
Все что нужно было от скрипта, это возможность применять его на любом элементе (включая DIVы
, параграфы, рисунки и т.д.) у которого был бы назначен CSS класс «toggle». Предыдущему элементу при этом добавляется элемент ссылки A с текстом или изображением show/hide.
Это правильный подход, достаточно хорошо работающий и на заголовках.
[w2hideshow]
Пример
- Мама мыла раму
- Рама мыла маму
- Мыло рама маму
Код
Первоначально код выглядел следующим образом.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
// Andy Langton's show/hide/mini-accordion - updated 23/11/2009 // Latest version @ // this tells jquery to run the function below once the DOM is ready $(document).ready(function() { // choose text for the show/hide link - can contain HTML var showText='Show'; var hideText='Hide'; // append show/hide links to the element directly preceding the element with a class of "toggle" $('.toggle').prev().append(' (<a href="#" class="toggleLink">'+showText+'</a>)'); // hide all of the elements with a class of 'toggle' $('.toggle').hide(); // capture clicks on the toggle links $('a.toggleLink').click(function() { // change the link text depending on whether the element is shown or hidden if ($(this).html()==hideText) { $(this).html(showText); } else { $(this).html(hideText); } // toggle the display - uncomment the next line for a basic "accordion" style $(this).parent().next('.toggle').toggle('slow'); // return false so any link destination is not followed return false; }); }); |
Код достаточно надежно работал с текстовыми ссылками и не хотел работать с ссылками изображениями. Он их просто не менял.
Слабое место:
1 |
if ($(this).html()==hideText) { |
JS в разных браузерах про разному интерпретировал сравнение кода картинки, поэтому решили переделать функцию переключения через проверочную переменную is_visible.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// initialise the visibility check var is_visible = false; // append show/hide links to the element directly preceding the element with a class of "toggle" $('.toggle').prev().append(' (<a href="#" class="toggleLink">'+showText+'</a>)'); // hide all of the elements with a class of 'toggle' $('.toggle').hide(); // capture clicks on the toggle links $('a.toggleLink').click(function() { // switch visibility is_visible = !is_visible; // change the link depending on whether the element is shown or hidden $(this).html( (!is_visible) ? showText : hideText); |
Но и в этом случае код не работал адекватно на множественных элементах с классом toggle.
В конце концов один из комментаторов предложил отказаться от переменной и переписать через проверку видимости самого класса toggle.
Изящное решение проблемы.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// this tells jquery to run the function below once the DOM is read $(document).ready(function() { // choose text for the show/hide link var showText="Show"; var hideText="Hide"; // append show/hide links to the element directly preceding the element with a class of "toggle" $(".toggle").prev().append(' <a href="#" class="toggleLink">'+showText+'</a>'); // hide all of the elements with a class of 'toggle' $('.toggle').hide(); // capture clicks on the toggle links $('a.toggleLink').click(function() { // change the link depending on whether the element is shown or hidden $(this).html( $(this).parent().next('.toggle').is(':visible') ? showText : hideText); // toggle the display $(this).parent().next('.toggle').toggle('slow'); // return false so any link destination is not followed return false; }); }); |