我有一大块 HTML 需要替换,其中包括 fadeOut
/fadeIn
过渡。我不知道如何将 HTML 添加到页面(隐藏)而不将其包装在 div 中。
$.get('/ajax', function(newHtml){
var $newEvent = $('<div class="new-event" />').hide().html(newHtml);
$('#content .event').fadeOut('slow', function(){
$(this).remove(); //old event
$newEvent.appendTo('#content').fadeIn('slow').removeClass('new-event'); //then remove the wrapper div that I didnt need in the first place
});
});
在利用最佳实践提高性能的同时,实现这一目标的最佳方法是什么?
解决方案:
出于某种原因,我认为创建像这样的新元素:$(newHtml)
比 html(newHtml)
效率低(性能差)。但显然,就性能而言,它们是相同的(除了我自己的观察之外,我没有数据支持这一点)。
因此下面的代码与前面的代码一样高效:
$.get('/ajax', function(newHtml){
var $newEvent = $(newHtml).hide();
$('#content .event').fadeOut('slow', function(){
$(this).remove(); //old event
$newEvent.appendTo('#content').fadeIn('slow');
});
});
最佳答案
将代码添加到页面时,将顶级元素全部隐藏
<div style="display:none;">...</div>
当 fadeIn
被调用时,jQuery 会自动为您删除它。
如果你无法修改返回的html,那么就这样做,
$(newHtml).hide().appendTo('#content');
这会在添加到 DOM 之前隐藏它。
关于javascript - 如何以最佳性能添加新的隐藏 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7421129/