打开媒体框并选择附件

时间:2016-08-23 作者:leemon

我使用以下代码在单击带有data-attachment_id 属性此属性保存框架打开时要选择的附件的id:

jQuery(document).ready(function($){

    $( \'#gallery_images_container\' ).on( \'click\', \'a.edit\', function( event ) {
        var $el = $( this );
        var selected = $( this ).attr( \'data-attachment_id\' );

        event.preventDefault();

        // If the media frame already exists, reopen it.
        if ( gallery_items_frame ) {

            // Select the attachment when the frame opens
            gallery_items_frame.on( \'open\', function() {
                var selection = gallery_items_frame.state().get( \'selection\' );
                if ( selected ) {
                    selection.add( wp.media.attachment( selected ) );
                }
            });

            // Open the modal.
            gallery_items_frame.open();

            return;
        }

        // Create the media frame.
        gallery_items_frame = wp.media.frames.gallery_items = wp.media({
            // Set the title of the modal.
            title: $el.data( \'choose\' ),
            button: {
                text: $el.data( \'update\' )
            },
            states: [
                new wp.media.controller.Library({
                    title: $el.data( \'choose\' ),
                    filterable: \'all\',
                    multiple: true
                })
            ]
        });

        // Select the attachment when the frame opens
        gallery_items_frame.on( \'open\', function() {
            var selection = gallery_items_frame.state().get( \'selection\' );
            if ( selected ) {
                selection.add( wp.media.attachment( selected ) );
            }
        });

        // Open the modal.
        gallery_items_frame.open();

    });

});
当我第一次单击链接时,框架将打开,并选择相关附件。但是,如果关闭框架并再次单击链接,框架将再次打开,但未选择任何附件。

关于我可能做错了什么,有什么见解吗?

提前感谢

1 个回复
最合适的回答,由SO网友:leemon 整理而成

嗯,我自己找到了答案。我希望它能帮助其他人:

我替换了以下两个实例:

if ( selected ) {
    selection.add( wp.media.attachment( selected ) );
}
使用:

selection.reset( selected ? [ wp.media.attachment( selected ) ] : [] );
显然reset() 函数可用于清空数组,然后向其中添加元素。