Простой повторно используемый скрипт JavaScript toggle ()? - PullRequest
0 голосов
/ 13 июня 2011

Я нахожусь в процессе изучения JavaScript и не уверен, как справиться с простым фрагментом повторно используемого кода.

Мне нужен фрагмент кода, который будет скрывать () # body01, # body02,# body03, 04,05 и т. д. (все они).Затем, когда я нажимаю title01, он понимает, что хочу toggle () body01.Если я нажму на title02, он переключится () body02 и т. Д.

<a id="title01">Title 1</a>
<div id="body01">Body content for Title 1</div>

<a id="title02">Title 2</a>
<div id="body02">Body content for Title 2</div>

<a id="title03">Title 3</a>
<div id="body03">Body content for Title 3</div>

Извините, если меня об этом попросили, я не смог ни найти его, ни разобраться сам.* Спасибо!

Ответы [ 4 ]

2 голосов
/ 13 июня 2011

Если вы используете jQuery (если нет, вам следует), это так просто:

$('[id^=title]').click(function(){

    var tmp = $(this).attr('id').split("title");
    $('#body'+tmp[1]).toggle();

});
1 голос
/ 13 июня 2011

Слишком часто новые разработчики JS переходят прямо в jQuery, не изучая сначала JavaScript как язык.Вы определенно должны изучить хотя бы какой-то простой JavaScript, чтобы вы могли лучше понимать и использовать мощные функции jQuery.Лучший способ переключения - установка и удаление класса, а не установка свойства стиля для элемента.Это значит, что вы можете сделать что-то вроде этого.

.hidden {display: none;}

    <div>
        <a id="title01" class="toggler">Title 1</a>
        <div class="body" id="body01">Body content for Title 1</div>

        <a id="title02" class="toggler">Title 2</a>
        <div class="body" id="body02">Body content for Title 2</div>

        <a id="title03" class="toggler">Title 3</a>
        <div class="body" id="body03">Body content for Title 3</div>
    </div>

    <script>
        // set your initial variables
        // ideally you will put these in a function which is not
        // exposed to the global object
        var togglers = document.getElementsByTagName('a'),
            divs   = document.getElementsByTagName('div'),
            i, j;

        // here you loop through your a elements and if they have
        // a class of toggler you assign the onclick event to a toggle function
        for ( i = 0; i < togglers.length; i += 1) {
            if (togglers[i].className == 'toggler') {
                togglers[i].onclick = toggle;
            }
        }

        function toggle() {
            // here you will cache the variable toToggle
            // which is the div you want to toggle
            var toToggle;

            // loop through all divs and if they have a class of body
            // you hide it
            for (j = 0; j < divs.length; j += 1) {
                if (divs[j].className == 'body') {
                    divs[j].className += ' hidden';

                    // this is tricky for a beginner. nodeType 1 is an element node
                    // nextSibling will get the nextSibling but if there is white space
                    // in your document it will return a text node when you have to toggle
                    // an element node. this just ensures that it will keep going until it
                    // finds and element node
                    if (this.nextSibling.nodeType !== 1) {
                        toToggle = this.nextSibling.nextSibling;
                    }
                    // then you toggle it by removing the hidden class
                    toToggle.className = 'body';
                }
            }
        }

    </script>
</body>

и вот несколько ссылок, которые ссылаются на nodeType и следующий брат.https://developer.mozilla.org/en/nodeType

https://developer.mozilla.org/En/DOM/Node.nextSibling

1 голос
/ 13 июня 2011

Вы можете сделать это с помощью jQuery, используя toggle метод:

$(function(){
  $("[id^=title]").click(function(){
    $(this).next().toggle();
    return false; // prevent moving down or going to link
  });
});
0 голосов
/ 13 июня 2011

Добавьте классы к своим элементам DOM, например:

<a class="title" id="title01" href="">Title 1</a>
<div class="body" id="body01">Body content for Title 1</div>

<a class="title" id="title02" href="">Title 2</a>
<div class="body" id="body02">Body content for Title 2</div>

<a class="title" id="title03" href="">Title 3</a>
<div class="body" id="body03">Body content for Title 3</div>

Затем вы можете добавить функцию переключения следующим образом:

$('.title').click(function(e){
    e.preventDefault();
    $(this).next('.body').toggle();
});

Вот демоверсия для функции, подобной jQuery

...