事件处理动态创建的HTML的最佳方式是什么? [英] What's the best way to event handle dynamically created HTML?

查看:125
本文介绍了事件处理动态创建的HTML的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理文档中的项目时,事件处理非常简单:

It's very easy to event-handle when dealing with items the document has from the get go:

$(document).ready(function() {
    $('.element-in-question').on("event", function (event) {
        //do what you need to do during the event
    });
});

我的问题是如何最好地处理动态元素。例如,假设我动态加载通知,其中一些是AJAX请求中的朋友请求。我会在成功回调中创建事件处理程序,还是在别的地方执行?

My problem is how would I best deal with dynamic elements. For example, let's say I dynamically load notifications, some of which are friend requests during an AJAX request. Would I create the event-handler in the success callback, or would I do it somewhere else?

我现在的方式是:

$(document).ready(function() {
    $.ajax({
        url: '/friendships/requests',
        type: 'GET', 
        success: function(responseData) {
            //dynamically create your elements (with classes accepted and rejected)
            $('.accepted, .rejected').on("click", function(event) {
                //do what is needed in this event
            });
        }
   });
});

这是一个惯用的方法,还是有另一种方式我可能应该去

Is this the idiomatic way to go about it, or is there another way I probably should be going about it?

推荐答案

使用jquery的on方法将事件处理程序绑定到父元素(不会更改)并传递选择器你想要听的元素:

use jquery's "on" merhod to bind event handler to parent element (which will not change) and pass a selector of the element you want to listen to:

$('.parent').on('event', '.child', handlerFunction);

这篇关于事件处理动态创建的HTML的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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