jQuery添加id到一个元素,被附加到主体

jQuery add id to an element that is being appended to the body

本文关键字:元素 一个 主体 id 添加 jQuery      更新时间:2023-09-26

我有以下功能:

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会让人感到困惑。我该怎么解决这个问题?由于

这是因为append方法返回要添加的元素,而不是要添加的元素。

相反,您可以使用appendTo方法,并按如下方式使用它;

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

您还需要使用$('#' + id)作为ID选择器,而不是$(id);否则,您将最终查找标签名称为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');