个性化阅读
专注于IT技术分析

$(this).parent().find()无法正常工作

点击下载

我正在制作一个显示图像的Wordpress小部件, 并使用Wordpress媒体上传器上传/更改该图像。

这是我正在使用的管理表单标记:

<p class="media-control"
    data-title="Choose an image"
    data-update-text="Choose image">

    <input class="image-url" name="image-url" type="hidden" value="">

    <img class="image-preview" src=""><br>
    <a class="button" href="#">Pick image</a>
</p>

当我单击” .media-control a”时, 将显示上载器, 我可以选择图像。但是, 当我选择图像” .image-preview”和” .image-url”时, 不会更新。

这是我的Javascript:http://jsfiddle.net/etzolin/DjADM/

除以下几行外, 一切都按预期工作:

jQuery(this).parent().find('.image-url').val(attachment.url);
jQuery(this).parent().find('.image-preview').attr('src', attachment.url);

当我这样写它们时, 将设置输入值并更新图像预览:

jQuery('.media-control .image-url').val(attachment.url);
jQuery('.media-control .image-preview').attr('src', attachment.url);

但是, 由于我使用了多个这些小部件中的一个, 因此它会更新每个小部件中的输入值和图像预览。

如何仅在我正在编辑的小部件中设置输入值并更新图像预览?我究竟做错了什么?


#1


在媒体框架的事件处理程序中, 这不是clicked元素

var media_frame;

jQuery('.media-control a').live('click', function (event) {

    var self = this;

    event.preventDefault();

    if (media_frame) {
        media_frame.open();
        return;
    }

    media_frame = wp.media.frames.media_frame = wp.media({
        title: jQuery(self).parent().data('title'), button: {
            text: jQuery(self).parent().data('update-text'), }, multiple: false
    });

    media_frame.on('select', function () {
        attachment = media_frame.state().get('selection').first().toJSON();

        jQuery(self).parent().find('.image-url').val(attachment.url); // set .image-url value
        jQuery(self).parent().find('.image-preview').attr('src', attachment.url); // update .image-preview
        //      ^^ this is not the element from the click handler but the media frame
    });

    media_frame.open();
});

并且你应该使用on(), 因为live()已弃用并从jQuery中删除

赞(0)
未经允许不得转载:srcmini » $(this).parent().find()无法正常工作

评论 抢沙发

评论前必须登录!