javascript $(this).parent().find() 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24100905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
$(this).parent().find() is not working
提问by Etzolin
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. But when I've picked an image ".image-preview" and ".image-url" isn't updated.
当我点击“.media-control a”时,上传器出现,我可以选择一张图片。但是当我选择一张图片时,“.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?
如何仅在我正在编辑的小部件中设置输入值并更新图像预览?我究竟做错了什么?
采纳答案by adeneo
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()
aslive()
已弃用并从 jQuery 中删除