简体   繁体   English

为什么JavaScript切换代码不起作用?

[英]why the javascript toggle code doesn't work?

I have added the Prototype library to my site, then add the following code. 我已将原型库添加到我的站点,然后添加以下代码。 but when i click the span, the ul content is not hidden. 但是当我单击范围时,ul内容不会被隐藏。 the link href still work. 链接href仍然有效。

Event.observe(window, 'load', function() {
    Event.observe('.block-category li.parent span', 'click', function(e){
        $('.block-category li.parent ul').toggle();
        e.preventDefault();

    });
});

html: HTML:

    <div class="block block-category">
    <li class="level-top  parent">
    <a href="example.com/...."><span>text one</span></a>
    <ul> //the 1 ul
    <li><a><span>....</span></a></li>
    <li><a><span>....</span></a></li>
    <li><a><span>....</span></a></li>
    <li><a><span>....</span></a></li>
    </ul>
    </li>

    <li class="level-top"><a href="..."><span>....</span></a></li>


  <li class="level-top  parent">
    <a href="example.com/...."><span>text two</span></a>
    <ul> //the 2 ul
    <li><a><span>....</span></a></li>

    </ul>
    </li>
  <li class="level-top  parent">
    <a href="example.com/...."><span>text three</span></a>
    <ul>
    <li><a><span>....</span></a></li>
    <li><a><span>....</span></a></li>
    </ul>
    </li>
    </div>

thank you. 谢谢。

ps : when click text one , the the 1 ul toggle. ps :单击文本一时 ,将1ul切换。 when click * text two *the 2 ul toggle, ... 当单击* 文本两个 * 2 ul切换时,...

You are using CSS selectors as arguments to Prototype's $() and Event.observe() functions. 您将CSS选择器用作Prototype的$()Event.observe()函数的参数。 Neither of these functions accepts a selector. 这些功能都不接受选择器。 They both expect element IDs instead. 他们都希望获得元素ID。

You can use $$() instead of $() and give it a selector. 您可以使用$$()代替$()并为其提供选择器。 Note that this returns an array of extended elements and not just a single one. 请注意,这将返回一组扩展元素,而不仅仅是单个元素。

http://api.prototypejs.org/dom/Event/observe/ http://api.prototypejs.org/dom/Event/observe/
http://api.prototypejs.org/dom/dollar/ http://api.prototypejs.org/dom/dollar/
http://api.prototypejs.org/dom/dollar-dollar/ http://api.prototypejs.org/dom/dollar-dollar/

You should try $$ to select multiple elements and then call observe for each one of them: 您应该尝试$$选择多个元素,然后为每个元素调用observe:

Event.observe(window, 'load', function() {
    $$('.block-category li.parent > a span').each(function (element) {
        element.observe('click', function (e) {
            e.element().up().next('ul').toggle();
            e.preventDefault();
        });
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM