javascript - 在 jQuery 中将事件绑定(bind)到元素的有效方法

标签 javascript jquery

我的页面中有一个 anchor 元素

<a href="..." id="page">Click</a>

我知道在 jQuery 中我们有很多方法将事件绑定(bind)到元素,例如(bind、live、delegate、on)。

仅供引用:

http://blog.tivix.com/2012/06/29/jquery-event-binding-methods/

当前使用jquery1.8.3.min.js。我想知道jQuery中标准且高效的事件注册模型是哪一种?

目前我正在这样做:

      $("#page").click(function(){
................................

    });

我可以更改为像下面的代码那样绑定(bind)吗:

$("#page").bind("click",clickFunc);

function clickFunc()
{
..........
}

在 jQuery 1.8 中注册事件的最佳实践是哪一种?

最佳答案

最好的方式是人们能够理解所写内容并且有效的方式。
聪明方式是使用建议使用的内容,在本例中为 .on()方法:

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()

操作方法方式取决于您是否需要将事件委托(delegate)给动态生成的元素。

$('.child').on( 'click', function() { /* ... */ });
$('#parent').on( 'click', ".dyn-gen-child", function() { /* ... */ });

关于javascript - 在 jQuery 中将事件绑定(bind)到元素的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20886455/

相关文章:

javascript - angularjs通过父级的索引获取td

javascript - 获取 TR 表外最接近的隐藏值

javascript - 从 karma 测试访问projectDir?

javascript - 触发 onInput 处理程序

javascript - 如果数量列的数值小于 10,如何更改表格行的背景颜色

javascript - 从同一个点击事件中停止两个或多个点击事件

jquery - 从一个 XML XSLT 到 HTML 制作两列

javascript - 如何检查所有异步任务是否已完成

javascript - 简单的客户端框架/模式来简化异步调用?

php - 从 Ajax 脚本重定向 Javascript 页面