-2

I would like to automatically turn list items into jQuery toggles for elements in a page.

For example, here is some sample page code:

<div id="page">
    <div id="menu">
        <ul>
            <li class="books">Books</li>
            <li class="cars">Cars</li>
            <li class="sausages">Sausages</li>
        </ul>
    </div>

    <div id="elements">
        <div class="books">This layer displays a range of books</div>
        <div class="cars">This layer displays a range of cars</div>
        <div class="sausages">This layer displays a range of sausages</div>
    </div>
</div>

As you can see, each menu list item and each element DIV, share the same class name.

What I would like to accomplish, with jQuery, is turning each menu list item automatically into a toggle, which can then toggles its corrosponding DIV in the elements section.

So it basically needs to read the menu items, then see if that menu item has a corrosponding element layer, and if so, turn it into a toggle which can toggle the layer.

It needs to be dynamic, because menu items and element layers might be added and removed regularly and it could eventually incorporate dozens of layers.

If this is possible, please demonstrate with a jsFiddle.

Thanks!

EDIT: I know how to use jQuery to hide and show specific elements on a page, where you hard code the element name into the code, however, I have no idea how to make it dynamic. I tried googling for at least 2 hours prior to posting here.

4

1 回答 1

2

上面的评论是正确的,你应该在你的帖子中付出更多的努力。除了 SO 不是“为我做作业”网站这一事实之外,您的描述对我来说很难理解。一些代码——甚至是伪代码——会有所帮助。

然而,我确实理解,有时我们甚至不知道我们不知道什么,这使得我们的问题很难沟通。因此,虽然我很难理解您想要什么,但如果我正确阅读它,这样的事情应该可以工作:

HMTL

<div id="page">
    <div id="menu">
        <ul>
            <li class="books">Books</li>
            <li class="cars">Cars</li>
            <li class="sausages">Sausages</li>
        </ul>
    </div>
    <hr />
    <div id="elements">
        <div class="books">This layer displays a range of books</div>
        <div class="cars">This layer displays a range of cars</div>
        <div class="sausages">This layer displays a range of sausages</div>
    </div>
</div>​

Javascript

$('#menu ul li').on('click', function () {
    var $matchingDIV = $('#elements div.' + $(this).attr('class'));

    $matchingDIV.toggle(!$matchingDIV.is(':visible'));
});​

这是小提琴

如果你在你的 LI 元素中添加了多个类名,它就会失败。另外,我不知道您是否希望元素开始显示,或者是否一次只显示一个,等等。希望您可以接受并运行它,但如果您对此有疑问,请提出。

于 2012-05-11T20:18:09.727 回答