【问题标题】:Wordpress custom image uploadWordpress 自定义图片上传
【发布时间】:2018-04-25 21:09:43
【问题描述】:

我需要在 wp 插件中使用自定义图像字段,上传/设置功能一切正常,但在更改图像时出现问题: 问题: 当我已经有一张图片并且需要替换时,我从媒体库中选择新图片并提交,旧的一张图片保持可见,所以我有两张图片可供查看。

我认为问题出在选择函数和附加部分,显然我在这里使用了错误的逻辑,下面是我的代码的 jquery+html 和问题的屏幕截图:

问题(两张图片): 第一个应替换为新的选择图像(第二个图像)

Two images screenshot

这是我的代码:

$('#btn-upload-image').on('click', function(e) {
        e.preventDefault();

        var button = $(this);
        var figure = button.siblings("figure");

        var custom_uploader = wp.media({
                title: 'Insert image',
                library: { type : 'image' },
                button: { text: 'Use this image' },
                id: 'library-' + (Math.random() * 10),
                multiple: false
            }).on('select', function() {
                var attachment = custom_uploader.state().get('selection').first().toJSON();
                figure.append( $('<img/>', { 'src': attachment.url }) );
                inputImage.val(attachment.url);
                inputImageId.val(attachment.id);
        })
        .open();
    });

和html:

<div class="form-group">
                        <label>Image</label>
                        <figure></figure>
                        <button type="button" class="btn btn-primary" id="btn-upload-image">Upload Image</button>
                        <input type="hidden" name="image" id="input-image" />
                        <input type="hidden" name="image_id" id="input-image-id" />
                    </div>

【问题讨论】:

    标签: javascript jquery wordpress


    【解决方案1】:

    问题来了:

    figure.append( $('&lt;img/&gt;', { 'src': attachment.url }) );

    append 在目标元素的末尾插入内容,保持现有内容不变。在这种情况下,您想要的是用新内容(新图像)替换其中的任何内容,因此:

    figure.html( $('&lt;img/&gt;', { 'src': attachment.url }) );

    html 将目标元素中的任何内容替换为新内容。

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 2012-01-18
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 2016-08-25
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多