使用jquery单击锚标记时如何切换ul类?

时间:2016-06-22 06:31:56

标签: jquery toggle

我想为ul li a保留切换功能。在magento中,我使用以下编码在分层导航中获取level 1level 2子类别:

<ul class="level0">
    <?php foreach ($cats as $cat): ?>
        <li class="level1">
            <a href="<?php echo $_helper->getCategoryUrl($cat) ?>">
                <?php echo $cat->getName() ?>
            </a>
            <?php $_category = Mage::getModel('catalog/category')->load($cat->getId()) ?>
            <?php $_subcategories = $_category->getChildrenCategories() ?>
            <?php if (count($_subcategories) > 0): ?>

                <ul class="level1" style="display:none;">
                    <?php foreach ($_subcategories as $_subcategory): ?>
                        <li class="level2">
                            <a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>">
                                <?php echo $_subcategory->getName() ?>
                            </a>
                        </li>
                    <?php endforeach; ?>
                </ul>

            <?php endif; ?>
        </li>

    <?php endforeach; ?>
</ul>

我想在点击ul.level1的{​​{1}}锚标签时切换并显示a。我使用下面的jquery:

level1

但点击<script> var $j = jQuery.noConflict(); $j(function () { $j('li.level1 a').click(function () { $j('ul.level1:visible').hide(); $j('ul.level1', this).toggle(); }); }); </script> 时未显示ul.level1。单击li.level1 a时切换。为什么会发生这种情况有助于我解决这个问题。

1 个答案:

答案 0 :(得分:1)

您可以使用siblings()

$(this).siblings("ul.level1").toggle();

这是jsfiddle

&#13;
&#13;
$('li.level1 a').click(function() {
    $(this).siblings("ul.level1").toggle();
});
&#13;
.level1{
  color:green;
}
.level2{
  color:yellow;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="level0">
<li class="level1">
  <a href="#">Toggle</a>
  <ul class="level1" style="display:none;">
  <li class="level2"><a href="#">Level2</a></li>
  <li class="level2"><a href="#">Level2</a></li>
  <li class="level2"><a href="#">Level2</a></li>
  </ul>
</li>
<li class="level1">
  <a href="#">Toggle</a>
  <ul class="level1" style="display:none;">
  <li class="level2"><a href="#">Level2</a></li>
  <li class="level2"><a href="#">Level2</a></li>
  <li class="level2"><a href="#">Level2</a></li>
  </ul>
</li>
<li class="level1">
  <a href="#">Toggle</a>
  <ul class="level1" style="display:none;">
  <li class="level2"><a href="#">Level2</a></li>
  <li class="level2"><a href="#">Level2</a></li>
  <li class="level2"><a href="#">Level2</a></li>
  </ul>
</li>
</ul>
&#13;
&#13;
&#13;