在将 ajax 内容添加到页面后,我无法实现对正在加载的 DOM 元素的影响。我的 console.log 打印出下面代码中显示的项目数,打印出 0,但是当我console.log($('.user-alert').length);
在 firebug 上运行它时,它打印出 2,这是正确的,因为我在页面上填充了 2 个元素。
这是我的代码:
( 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));