2011-11-07 44 views
1

我有以下功能:jQuery的添加ID到正在附加到主体上的元件

simpleModal: function (data, id) { 

     var responseHtml = data; 

     // Append the modal HTML to the DOM 
     var modalInstance = $('body').append(modalHtml); 

     $(modalInstance).attr('id', id); 

     $(id).find('.uiModalContent').width(480); 
     $(id).find('.uiModalContent').height(320); 

     // Hide the modal straight away, center it, and then fade it in 
     $(id).find('.uiModal').hide().center().fadeIn(); 

     // Dynamically load in the passed data from the call 
     $(id).find('.uiModalContent').html($(responseHtml)); 
     $(id).find('.uiModalContent').removeClass('loading'); 

     $(id).find('.ModalClose').live('click', function (e) { 
      e.preventDefault(); 
      $(this).parents('.uiModal').fadeOut(function() { $(this).parents('.uiModalWrapper').remove() }); 
     }); 
    }, 

时调用,如:

uiModal.simpleModal('<p>An error has occured</p>','TestError');

应该模态追加到体与传递的内容,并给modalHtml一个ID也是通过。然而它会混淆添加id到body而不是html。我如何解决这个问题?谢谢

+0

_modalInstance_是您的身体元素。那就是问题所在。 - '$(modalInstance).attr('id',id); // var modalInstance = $('body')...' – Smamatti

回答

2

这是因为append方法返回您要附加到的元素,而不是您要追加的元素。

取而代之,您可以使用appendTo方法,并按以下方式使用它;

var modalInstance = $(modalHtml).appendTo('body'); 

您还需要使用$('#' + id)作为,而不是$(id)ID selector;否则你会结束looking for all elements with the tag name of TestError.

另外,你应该严重考虑缓存结果$('#' + id);您正在执行6次相同的DOM查找操作;这是完全不必要的,因为你有完全相同的jQuery对象,缓存在var modalInstance;将$('#' + id)的所有实例替换为modalInstance

此点同样适用于$(id).find('.uiModalContent');缓存它!

var uiModelContent = modelInstance.find('.uiModalContent'); 
uiModelContent.height(320); 
uiModelContent.width(480); 
uiModelContent.html($(responseHtml)); 
uiModelContent.removeClass('loading'); 

虽然你也可以连接你的相同结果的方法;

modelInstance.find('.uiModalContent').height(320).width(480).html($(responseHtml)).removeClass('loading');