常见问题下拉列表

常见问题下拉列表

我试图创建一个简单的常见问题下拉列表,但由于某种原因它无法正常工作。您介意看看吗?

谢谢你们!

的CSS

#faqs h3    { cursor:pointer; }
#faqs h3.active { color:#d74646; }
#faqs div { height:0; overflow:hidden; position:relative; }
#faqs div p { padding:0; margin-bottom:15px; }


JavaScript:

$(document).ready(function() {
    $('#faqs h3').each(function() {
        var tis = $(this),
            state = false,
            answer = tis.next('div')
                        .hide()
                        .css('height','auto')
                        .slideUp();

            tis.click(function() {
                state = !state;
                answer.slideToggle(state);
                tis.toggleClass('active',state);
            });
    });
});


的HTML

<div id="faqs">
    <h3>This is question 1?</h3>
        <div>
            <p>This is the answer to question #1.</p>
        </div>
    <h3>This is question 2?</h3>
        <div>
            <p>This is the answer to question #2.</p>
        </div>
</div>

最佳答案

以下功能可用于您需要的功能:

的HTML

<div id="QA">
  <ul>
    <li>Question 1</li>
    <li>Answer 1</li>
    <li>Question 2</li>
    <li>Answer 2</li>
  </ul>
  <ul>
    <li>Question 3</li>
    <li>Answer 3</li>
    <li>Question 4</li>
    <li>Answer 4</li>
  </ul>

</div>


JavaScript:

<script type="text/javascript">
    function toggle(tag) {
        var x=document.getElementsByName(tag)[0];
        var a = x.parentNode
        if (a.style.display=='block'){
            a.style.display='none'
        }else{
            a.style.display='block'
        }
    }


    function init() {
        //this function will add show hide functionality to paired list items,
        //as long as the answer is a list item straight after the question list item.
        //You can also have as many separate lists as you want.
        //all lists must be contained within a div with id QA

        var obj = document.getElementById('QA');
        var elements = obj.getElementsByTagName('li');
               var index = 1
        //add javascript to question elements
              //you could also add styling to question elements here
        for (var i=0; i < elements.length; i+=2){
            var element = elements[i];
            element.innerHTML = "<a href='javascript:toggle(" + index + ")'>" + element.innerHTML + "</a>"
            index = index + 1
        }
        //add bookmark to answer elements and add styling
        var index = 1
        for (var i=1; i < elements.length; i+=2){
            var element = elements[i];
            element.innerHTML = "<a name='" + index + "' id='" + index + "'></a>" + element.innerHTML
            index = index + 1
                 element.style.padding = '0px 0px 10px 20px' //add indent to answer
                       element.style.listStyleType = 'none' //remove bullet
            element.style.display = 'none' //hide answer element
        }
     }


window.onload = init;

</script>

09-25 19:36