我陷入了困境,它的worpress mediauploader。我想上传图片,一个功能是一个图像但我有几个上传按钮具有唯一的ID所以我只想要一个功能,为什么我创建循环,点击每个按钮媒体上传开放,但有问题保存选中的图像,我没有在值中获得该图像的URL。请帮助jquery和javascript新手。尝试了各种方法,这是其中之一 这是我想要的屏幕截图 - > here
jQuery(document).ready(function($){
var b = ["#upload-button-1", "#upload-button-2", "#upload-button-3","#upload-button-4","#upload-button-5","#upload-button-6","#upload-button-7","#upload-button-8"];
var d =[".procircle-1", ".procircle-2",".procircle-3",".procircle-4",".procircle-5",".procircle-6",".procircle-7",".procircle-8"];
var j;
var c = ["#grid-image-1", "#grid-image-2", "#grid-image-3","#grid-image-4","#grid-image-5","#grid-image-6","#grid-image-7","#grid-image-8"];
var i;
for(i=0; i<=b.length; i++)
{
for(j=0;j<=c.length;j++){
$(b[i]).on('click',function(e){
e.preventDefault();
if( mediaUploader ){
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame= wp.media({
title:'Choose a Picture for Procedure ',
button:{
text:'Choose Picture'
},
multiple:false
});
mediaUploader.on('select',function(){
attachment= mediaUploader.state().get('selection').first().toJSON();
$(c[j]).val(attachment.url);
$('.procircle-2').css({'background':'url(' + attachment.url + ')','background-repeat': 'no-repeat'});
});
mediaUploader.open();
});
}
}
});
答案 0 :(得分:0)
我建议你做以下事情(如果你必须保留你的ids等):
$(document).on('click', '#upload-button-1, #upload-button-2, #upload-button-3, #upload-button-4, #upload-button-5, #upload-button-6, #upload-button-7, #upload-button-8', function(e) {
var match = e.target.id.match(/(\d+)/g);
e.preventDefault();
if(mediaUploader) {
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame = wp.media({
title:'Choose a Picture for Procedure ',
button:{
text:'Choose Picture'
},
multiple:false
});
mediaUploader.on('select', function(){
var attachment = mediaUploader.state().get('selection').first().toJSON();
var id = '#grid-image-' + match[1];
$(id).val(attachment.url);
$('.procircle-2').css({'background':'url(' + attachment.url + ')','background-repeat': 'no-repeat'});
});
mediaUploader.open();
});
这将删除循环并委托您的处理程序,因此您只需创建一个单击处理程序,而不是像当前一样每循环迭代创建一个单击处理程序,并且还创建单个mediauploader选择处理程序。最后,将相应的输入与执行单击的事件目标相匹配。应该工作,虽然你可能需要稍微玩一下,它肯定会被重构为更好。希望它有所帮助。