在我的网站上,我动态添加了很多 HTML 内容(来自 ajax 请求),因此我必须大量使用委托(delegate),以便 JS 代码可以处理添加的 HTML 内容。我最近构建了自己的全页面 ajax,其中页面在每次链接点击和表单搜索时都使用 ajax 加载。由于这个整页 ajax,我的所有事件都必须委托(delegate)给正文或文档:
$(document).ready(function() {
$('body').on('click', '.example1', exampleHandler1);
$('body').on('click', '.example2', exampleHandler2);
$('body').on('submit', '.example3', exampleHandler3);
$('body').on('mouseover', '.example4', exampleHandler4);
// etc.
});
我已经有 30 个事件监听器,将来可能还会有超过 100 个事件监听器,所以我不知道如果我有超过 100 个事件都委托(delegate)给主体,这会对性能产生多大影响。
我不确定以下方式是否会更好:
每当添加 HTML 内容时,我都可以重新触发所有代码。这也意味着我根本不必使用委托(delegate):
// Trigger the custom event on ready so it runs when a user first visits the page
$(document).ready(function() {
$(document).trigger('exampleCustomEvent');
});
// using a custom event
$(document).on('exampleCustomEvent', function() {
$('.example1').on('click', exampleHandler1);
$('.example2').on('click', exampleHandler2);
$('.example3').on('submit', exampleHandler3);
$('.example4').on('mouseover', exampleHandler4);
// etc.
});
/**
* Re-trigger the custom event.
*
* Call this whenever dynamic content is added.
*/
function triggerCustomEvent() {
// Remove any event listeners first
$('*').off();
$(window).off();
// Trigger the custom event
$(document).trigger('exampleCustomEvent');
}
然后我只需在添加 HTML 内容时调用 triggerCustomEvent()
即可。
哪一个更好,还有其他解决方案吗?
最佳答案
根据您要导入的功能类型,您可以包含新 HTML 所需的 JS,或者甚至可以仅在 HTML 中包含 JS 调用以再次初始化函数。 如果 JS 功能是通用的,并且您不想在每次调用时传递它,那么我建议只初始化该部分。您甚至可以将包装器的选择器传递给初始化所有内容的函数,并将其附加到每个选择器的开头。
function init(){
$('#contentWrapper #test').click(function(){console.log("ouch!");})
}
//code from ajax-->:
$('#contentWrapper').html(
'<script>init(); $("#contentWrapper #test").click(function(){'+
'console.log("unique functionality to this ajax call.");})</script>'+
'<button id="test">CLICK ME</button>'
)
关于Javascript:让 JS 处理大量动态添加的 HTML 内容的最佳方法。委托(delegate)/重新触发/或其他?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48548122/