javascript - $(this).parent().find() 不工作

标签 javascript jquery jquery-selectors wordpress-theming this

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

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

<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”时, uploader 出现,我可以选择一张图片。但是当我选择了一张图片时,“.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);

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

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

最佳答案

在媒体框架的事件处理程序中 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();
});

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

关于javascript - $(this).parent().find() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24100905/

相关文章:

javascript - 遍历dom,next,prev

javascript - 谁能解释这段 Javascript 中发生了什么?

javascript - 如何设置在页面加载时更改的 div 的整页背景图像

javascript - 如何将文本区域链接到提交 PHP

jquery - 如何使用 jQuery.tmpl() 插件仅传入字符串[],而不是对象

jquery - 如何检测选择器是否返回 null?

javascript - 打印出迭代中的每个数组值,值是未定义的

javascript - 在数组中查找对象并更改其属性(如果我知道它的其他属性)

javascript - Document.Open() 不起作用

jquery - 用于选择名称不以 "something"开头/结尾的元素的选择器