我有以下功能:
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添加到正文而不是html会很困惑。我该如何解决这个问题?感谢
答案 0 :(得分:2)
这是因为append
方法返回您要追加的元素,而不是您要追加的元素。
相反,您可以使用appendTo
方法,并按如下方式使用它;
var modalInstance = $(modalHtml).appendTo('body');
您还需要使用$('#' + id)
作为ID selector,而不是$(id)
;否则你最终会looking for all elements with the tag name of TestError
.
此外,您应认真考虑缓存$('#' + id)
的结果;您正在执行相同的DOM查找操作6次;这是完全没必要的,因为你在var modalInstance
中缓存了完全相同的jQuery对象;将$('#' + 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');