简体   繁体   English

如何使用原型的观察记录div中的每次点击

[英]How to register every click inside a div using prototype's observe

I am trying to create a simple application that needs to hide and show div content on click. 我正在尝试创建一个简单的应用程序,该应用程序需要在单击时隐藏和显示div内容。 It fine except for the fact that any time I click on a span or the list, the div doesn't observe a click. 除了我每次单击范围或列表时,div都不会观察到单击,这很好。 What is the best way to observe all the clicks within this div? 观察此div中所有点击的最佳方法是什么?

 <div data-hour="16" data-minute="0" data-duration="1" class="even">
          <span class="title" >block:</span> <span>4:00PM</span>
            <div>
                <ul>
                    <li>item 1</li>
                    <li>item 2</li>
                </ul>
            </div>
        </div>


$$('#contents >  div').each(function(item) {
        item.observe('click', respondToClick);
    });

Unless you're catching and suppressing the clicks via handlers on the span or list, your code above should be working, and it does here: http://jsbin.com/etuka3 (That observe code can be shortened, though, via invoke : http://jsbin.com/etuka3/2 ). 除非您通过跨度或列表上的处理程序来捕获和抑制点击,否则上面的代码应该可以正常工作,并且可以在此处进行操作: http : //jsbin.com/etuka3 (不过,可以通过invoke来缩短observe代码: http : //jsbin.com/etuka3/2 )。

As I'm sure you know, most DOM events "bubble" up from an element to its parent element to its parent element, etc., unless the bubbling is cancelled by an event handler somewhere in the chain. 正如我敢肯定你知道,大多数DOM事件“泡”了从元素到其父元素父元素等等,除非冒泡是由一个事件处理链中某处取消。 For instance, in this version of the above, I hook click on the li s and prevent the event reaching the div : 举例来说,在这个版本以上的,我勾clickli S和防止事件到达div

$$('#contents > div li').invoke('observe', 'click', function(event) {
    event.stopPropagation(); // Prevents the event from bubbling up to the ancestors
});

...which means clicking an li , the div doesn't see the click. ...这意味着点击lidiv看不到点击。 But you have to do that on purpose, just hooking an event on a child element does not prevent bubbling, as you can see in this example : 但是您必须故意这样做,仅将事件挂接到子元素上并不能防止冒泡,如本例所示

$$('#contents > div li').invoke('observe', 'click', function(event) {
    display("list item clicked");
});

Now when I click an li , we can see that the li 's handler gets triggered, and then (because I didn't stop bubbling), the div 's handler gets triggered. 现在,当我单击li ,我们可以看到li的处理程序被触发,然后(因为我没有停止冒泡),因此div的处理程序被触发了。

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

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