简体   繁体   English

$(this).parent()。find()不起作用

[英]$(this).parent().find() is not working

I am making a Wordpress widget showing an image, and to upload/change this image I use the Wordpress media uploader. 我正在制作一个Wordpress小部件显示图像,并上传/更改此图像我使用Wordpress媒体上传器。

This is the admin form markup I'm using: 这是我正在使用的管理表单标记:

<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>

When I click ".media-control a" the uploader appears and I can pick an image. 当我点击“.media-control a”时,会出现上传器,我可以选择一张图片。 But when I've picked an image ".image-preview" and ".image-url" isn't updated. 但是当我选择了一个图像“.image-preview”和“.image-url”没有更新。

Here's my javascript: http://jsfiddle.net/etzolin/DjADM/ 这是我的javascript: http//jsfiddle.net/etzolin/DjADM/

Everything is working as intended except these lines: 一切都按预期工作,除了这些线:

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

When I write them like this, input value is set and image preview is updated: 当我这样写它们时,设置输入值并更新图像预览:

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

But since I use more than one of these widgets it updates the input value and image preview in every widget. 但由于我使用了多个这些小部件,因此它会更新每个小部件中的输入值和图像预览。

How can I set the input value and update the image preview only in the widget I'm editing? 如何设置输入值并仅在我正在编辑的小部件中更新图像预览? What am I doing wrong? 我究竟做错了什么?

Inside the event handler for the media frame this is not the clicked element 在媒体框架的事件处理程序内部, this不是单击的元素

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();
});

and you should be using on() as live() is deprecated and removed from jQuery 你应该使用on()因为live()已被弃用并从jQuery中删除

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM