0
在將ajax內容添加到頁面後,我正在執行對正在加載的DOM元素的效果時遇到問題。我的console.log打印出下面代碼中顯示的項目數,但輸出0,但是當我在螢火蟲上運行console.log($('.user-alert').length);
時,它打印出2,這是正確的,因爲我在頁面上填充了2個元素。在Ajax內容加載後使用jQuery
這裏是我的代碼:
(function($) {
Drupal.behaviors.alerts = {
attach: function (context) {
var InfiniteRotator =
{
init: function()
{
//initial fade-in time (in milliseconds)
var initialFadeIn = 1000;
//interval between items (in milliseconds)
var itemInterval = 5000;
//cross-fade time (in milliseconds)
var fadeTime = 2500;
//count number of items
var numberOfItems = $('.user-alert').length;
console.log(numberOfItems);
//set current item
var currentItem = 0;
//show first item
$('.user-alert').eq(currentItem).fadeIn(initialFadeIn);
//loop through the items
var infiniteLoop = setInterval(function(){
$('.user-alert').eq(currentItem).fadeOut(fadeTime);
if(currentItem == numberOfItems -1){
currentItem = 0;
}else{
currentItem++;
}
$('.user-alert').eq(currentItem).fadeIn(fadeTime);
}, itemInterval);
}
};
InfiniteRotator.init();
}
};
}(jQuery));
下面是HTML林試圖目標:
<div class="block block-user-alert contextual-links-region block-user-alert block-user-alert-user-alert odd" id="block-user-alert-user-alert">
<div id="user-alert-45" class="user-alert">
<div class="user-alert-close"><a href="javascript:;" rel="45">x</a></div>
<div class="user-alert-message"><span class="user-label">User Alert:</span> Test Alert 2</div>
</div>
<div id="user-alert-43" class="user-alert" style="display: none;">
<div class="user-alert-close"><a href="javascript:;" rel="43">x</a></div>
<div class="user-alert-message"><span class="user-label">User Alert:</span> Test Alert 3</div>
</div>
</div>
這是AJAX,也記住這個代碼是從貢獻的Drupal模塊,不應該修改:
(function ($) {
Drupal.behaviors.user_alert_get_message = {
attach: function(context) {
$.ajax({
type: 'GET',
url: Drupal.settings.basePath + Drupal.settings.user_alert.url_prefix + 'js/user-alert/get-message',
success: function(response) {
var id = $('.block-user-alert').attr('id');
$('#' + id).html(response[1].data);
}
});
$('body').delegate('div.user-alert-close a', 'click', function() {
id = $(this).attr('rel');
$.ajax({
type: 'GET',
data: 'message=' + id,
url: Drupal.settings.basePath + Drupal.settings.user_alert.url_prefix + 'js/user-alert/close-message',
success: function(response) {
$('#user-alert-' + id).fadeOut('slow');
}
});
});
}
};
}(jQuery));
你提到用AJAX添加圖像。你能發佈這樣的代碼嗎? –
當然,儘管ajax的問題被稱爲貢獻代碼,所以我不應該修改它。 – Novazero
不能幫助Drupal,插件..你可能想閱讀http://drupal.stackexchange.com/questions/42148/drupals-attach-behaviours-react-on-all-newly-loaded-content上的評論也許後在那裏,因爲它是一個Drupal特定的stackexchange網站.. –