[英]$(this).parent().find() is not working
我正在制作一個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);
但由於我使用了多個這些小部件,因此它會更新每個小部件中的輸入值和圖像預覽。
如何設置輸入值並僅在我正在編輯的小部件中更新圖像預覽? 我究竟做錯了什么?
在媒體框架的事件處理程序內部, 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中刪除
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.