什么是正确的方法使用AJAX来获取HTML内容之后添加侦听新的元素呢? (jQuery的,使用Javascript) [英] What is a proper way to add listeners to new elements after using AJAX to get the html content? (jQuery, Javascript)

查看:127
本文介绍了什么是正确的方法使用AJAX来获取HTML内容之后添加侦听新的元素呢? (jQuery的,使用Javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提出了通过AJAX可以加载新的设置页面,我不知道什么是从新的内容页面绑定听众的内容,其中最有效的方法什么?

I am making something that can loads new setting pages via AJAX, I am not sure what's the most efficient way to bind listeners to those elements from the new content page?

下面是我的想法。我可以做一个功能比较文件的路径,并为每个条件,那么我会正确的监听器适用于基于什么页面,AJAX加载这些新的元素。我觉得这将使得功能如此之大,如果我有大量的页面。

Here's my thought. I can make a function that compares file path, and for each condition, then I will apply correct listeners to those new elements based on what page that AJAX loaded. I feel like it will makes the function so big if I have a large amount of pages.

谢谢!

推荐答案

有两种方式:

1)使用非动态父容器绑定。对()

1) Bind on a non-dynamic parent container using .on()

$('.some-parent-class').on('click', '.element', function() {
  // DO STUFF!
});

2)绑定新的元素Ajax调用完成后,

2) Bind the new elements after ajax call is completed

$.ajax(url, {
  // ajax options
}).done( function(data) {
  var newEl = $('<div class="element"></div>');
  // Setup your newEl with data here...
  newEl.on('click', function() {
    // do stuff
  });
  newEl.appendTo($('.some-parent-class'));
});

,前者通常会导致更快的Ajax响应时间,但可以也慢点击响应速度下降。

The former usually results in quicker ajax response times, but may also slow click responsiveness down.

这篇关于什么是正确的方法使用AJAX来获取HTML内容之后添加侦听新的元素呢? (jQuery的,使用Javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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