我提出了通过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.