我有一个附件id,但我需要一个url。如何从附件对象获取url?
// When an image is selected, run a callback.
frame.on( \'select\', function() {
// Grab the selected attachment.
var attachment = frame.state().get(\'selection\').first();
$(\'#\' + id).val(attachment.id);
});
。。。
函数将其转换为toJSON。现在它工作了。
jQuery(document).ready(function($) {
var frame;
// Build the choose from library frame.
$(document).on("click", ".upload_image_button", function() {
var id = $(this).attr(\'id\').replace(\'_b\', \'\');
if ( frame ) {
frame.open();
return;
}
// Create the media frame.
frame = wp.media.frames.meta_image_frame = wp.media({
// Tell the modal to show only images.
library: {
type: \'image\'
},
});
// When an image is selected, run a callback.
frame.on( \'select\', function() {
// Grab the selected attachment.
attachment = frame.state().get(\'selection\').first().toJSON();
$(\'#\' + id).val(attachment.url);
});
frame.open();
});
});
最合适的回答,由SO网友:Iftieaq 整理而成
您必须使用toJSON()将附件变量转换为JSON对象。然后,您可以查看其属性。
使用
attachment = frame.state().get(\'selection\').first().toJSON();
而不是
attachment = frame.state().get(\'selection\').first();