我試圖將點擊處理程序綁定到DOM上的幾個元素。點擊後,該元素會在shadowbox中加載一些新內容。在玩了一段時間的代碼之後,我發現每次點擊時都會花費更長的時間。jQuery單擊很多點擊後緩慢運行
我通過禁用除簡單console.log之外的所有click處理函數來測試此功能。即使在此之後,通過第15次點擊,響應變得越來越慢。無論我點擊哪個帖子,或者即使內容已被加載,在第15次單擊此「.shadowbox-link」元素時,它的確會開始減速。
這裏是我的點擊處理程序:
$j('#content article .shadowbox-link').bind('click', showShadowboxPost);
肚裏的功能:
var showShadowboxPost = function() {
// Unbind click handler
$j(this).unbind('click', showShadowboxPost);
// Variables for ajax request
var postData = {
'postId': $j(this).attr('data-id'),
'postType': $j(this).attr('data-type'),
'elementId': $j(this).attr('id'),
'prevPost': $j(this).prev().attr('id'),
'nextPost': $j(this).next().attr('id')
};
preFadeIn();
// If content already loaded, avoid ajax request
// The following functions include the fadeIn
if($j(this).children('.single-post').length !== 0) {
preLoadedRequest(this)
} else {
ajaxRequest(postData, this)
}
// Rebind click handler
$j(this).bind('click', showShadowboxPost);
return false;
};
這裏
全部文件:http://www.clarkthomasny.com/wp-content/themes/cleanslate/js/shadowbox-post.js
的HTML基本上是這樣的:
<div id="content">
<div id="articles">
<article class="shadowbox-link"></article>
<article class="shadowbox-link"></article>
<article class="shadowbox-link"></article>
[etc..]
</div>
</div>
這裏是頁的位置:http://www.clarkthomasny.com/
我試圖調試這幾種不同的方式,但我仍然不知道發生了什麼事情,並認爲它必須是與單擊處理程序綁定到這麼多的元素呢?幾年來,我一直在使用jQuery,並且我很難過,請幫助。謝謝!
爲什麼你解綁並綁定相同的句柄到處理器內部的元素 –
它不會導致你提到的漸進式減速,但是因爲你問的是性能,你不應該繼續調用'$ j(這個)'在整個函數中 - 緩存在一個變量中。 – nnnnnn
還沒有on()替換bind()?使用新方法會對性能產生影響嗎? – Seano666