jQuery:绑定一个可以处理其子事件的事件监听器 [英] jQuery: binding a single event listener that can handle events of its children

查看:84
本文介绍了jQuery:绑定一个可以处理其子事件的事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个我不知道解决方案的问题。

I encountered a question to which I didn't know the solution for.

假设我有这个HTML标记(由服务器动态生成或只是静态文件):

Suppose I have this HTML markup (dynamically generated by the server or simply a static file):

<ul class="myList">
<li><a href="page1.html">Page 1</a></li>
<li><a href="page2.html">Page 2</a></li>
<li><a href="page3.html">Page 3</a></li>
<li><a href="page4.html">Page 4</a></li>
<li><a href="page5.html">Page 5</a></li>
<li><a href="page6.html">Page 6</a></li>
<!-- ... -->
<li><a href="page1000.html">Page 1000</a></li>
</ul>

我想将点击事件处理程序绑定到< a>标签。通常情况下,我会写出

I want to bind a click event handler to the <a> tag. Normally, I would write out

$('.myList').find('a').click(function() {});  /* Or something similar */

会对所有锚标签执行隐式迭代以绑定点击对他们每个人的事件。但是,我被告知这是一项昂贵的操作。

which would perform implicit iteration on all the anchor tags to bind a click event to each of them. However, I was told that this is an expensive operation.

我被问到是否有某种方法只能连接一个事件监听器(在ul标签上)并使用事件冒泡以找出点击了哪个锚标签。我从未遇到过这样的事情,所以我不知道答案。显然,有一个答案。有人知道如何在元素上放置单个事件监听器并让它知道单击了哪个子元素吗? (我仍然需要使用event.preventDefault()来阻止默认的点击事件。)

I was asked if there was some way to attach only one event listener (on the ul tag) and use event bubbling to figure out which anchor tag was clicked. I have never encountered something like this, so I didn't know the answer. Apparently, there is an answer. Does anybody know how to place a single event listener on an element and have it figure out which child element was clicked? (I still need to use event.preventDefault() to prevent the default click event.)

推荐答案

签出 delegate() —这正是你所要求的。

Check out delegate() — it's exactly what you're asking for.

$('ul.mylist').delegate('a', 'click', function() {
  // ... your code ...
});

您可以获得jQuery处理程序的所有好处,而无需对所有这些元素进行绑定。

You get all the benefits of a jQuery handler, without having to do the binding to all those elements.

这篇关于jQuery:绑定一个可以处理其子事件的事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆