最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Multiple media uploader buttons target only one input on the same page

programmeradmin0浏览0评论

I want to call the wordpress media uploader with a button in my theme options page. The thing is that I need two upload media buttons on the same page. I'm trying to do that using javascript by getting the element that triggered the click event then assign the url to the input and the preview image. The code is working fine: I click the button and the media uploader is launched, however when I upload anything into the first input field, the media that I just uploaded is passed on to the other input fields in the page. Like they were bonded together.

php:

function image_larg_cb(){
    $image_upload_larg = esc_attr( get_option("handler_larg"));
    echo    "<div class='upload-btn-box'>
                <input class='button button-secandary' data-input='upload_larg' type='button' value='upload' id='input_larg_btn'/>
                <input type='hidden' id='input_larg' name='handler_larg'  value='"  . $image_upload_larg . "'/>
                <img id='image_larg' src='" . $image_upload_larg . "'/>
            </div>";
}


function image_icon_cb(){
    $image_upload_icon = esc_attr( get_option("handler_icon"));
    echo  "<div class='upload-btn-box'>
            <input class='button button-secandary'  data-input='upload_icon'  type='button' value='upload' id='input_icon_btn'/>
            <input type='hidden' id='input_icon' name='handler_icon' value='"  . $image_upload_icon . "'/>
            <img id='image_icon' src='" . $image_upload_icon . "'/>
            </div>";
}

javascript:

let mediaUploader,
    wpbody = document.querySelector("#wpbody"),
    input_larg = document.querySelector("#input_larg"),
    img_larg = document.querySelector("#image_larg"),
    input_icon = document.querySelector("#input_icon"),
    img_icon = document.querySelector("#image_icon");

wpbody.addEventListener('click', mUploader);

function mUploader(event) {
  let target = event.target.dataset.input;

  if (target == "upload_larg" || target == "upload_icon") {
      console.log(event.target )
    event.preventDefault();
    if (mediaUploader) {
      mediaUploader.open();
      return;
    }
    mediaUploader = wp.media.frames.file_frame = wp.media({
      title: 'icon_icon',
      button: {
        text: 'Choose Picture'
      },
      multiple: false
    })
    mediaUploader.on("select", function() {
      attachment =
        mediaUploader.state().get('selection').first().toJSON();
      if (target == "upload_larg") {
        input_larg.value = attachment.url;
        img_larg.src = attachment.url;

      }
      if (target == "upload_icon") {
        input_icon.value = attachment.url;
        img_icon.src = attachment.url;

      }
    });
    mediaUploader.open();
  }
};
发布评论

评论列表(0)

  1. 暂无评论