替换孩子并保持父母

时间:2017-08-18 14:53:01

标签: jquery

我想问一个关于此的问题: "如何用其他元素替换子元素,然后将父元素应用于文档。" 我尝试使用replaceWith(),但没有为我提供解决方案。 这是我的代码:

template_gallery = '<div class="mahbub-modal">'+
        '<button type="button" class="mahbub-btn-close">'+elmahbub.btn_close+'</button>'+
        '<div class="mahbub-modal-gallery">'+
        '<div class="mahbub-gallery-content">'+
        '<div class="mahbub-column-left">'+
        '<img src="'+elmahbub.source+'" class="mahbub-image" alt="'+elmahbub.alt_image+'">'+
        '<div class="mahbub-btn-more">'+
        '<button type="button" class="mahbub-more-left" title="'+elmahbub.title_prev_button+'">&#10094;</button>'+
        '<button type="button" class="mahbub-more-center" title="'+elmahbub.title_center_button+'">'+elmahbub.icon_btn_center+'</button>'+
        '<button type="button" class="mahbub-more-right" title="'+elmahbub.title_next_button+'">&#10095;</button>'+
        '</div>'+
        '<div class="mahbub-gallery-footprint">'+elmahbub.title+
        '<p class="mahbub-gallery-footprint-subtitle">'+elmahbub.sub_title+'</p>'+
        '</div>'+
        '</div>'+
        '<div class="mahbub-column-right">'+elmahbub.content+
        '</div>'+
        '</div>'+
        '</div>';

Jquery:

if (elmahbub.type == 'video') {
        video_element = '<video width="100%" height="500px" controls>'+
        '<source src="'+elmahbub.source+'" type="video/ogg">'+
        '<source src="'+elmahbub.source+'" type="video/mpeg">'+
        elmahbub.error_load+'</video>';
        if (elmahbub.gallery[0].enabled == false) {
            template_gallery = $(template_gallery).children($('.mahbub-image')).replaceWith(video_element);
            modal = template_gallery;
        }
        else{

        }
    }

我想模板库有元素视频:-) 感谢。

1 个答案:

答案 0 :(得分:4)

使用jQuery来识别目标父级,而不是使用html函数来附加子级。

$('#parent-div').html("<h1>test</h1>");

如果你想用现有的DOM元素替换而不是这样做......

$('#parent-div').html($('#divIWant'));