Добавить параметр в JS

304
20 октября 2017, 16:08

Делаю мультизагрузку изображений с помощью Dropzone.js

<button class="btn" data-id="uniq_first">Btn1</button>
<button class="btn" data-id="uniq_second">Btn2</button>
<div id="dialog" title="Basic dialog">
    <div id="actions" class="row">
      <div class="col-lg-7">
        <!-- The fileinput-button span is used to style the file input field as button -->
        <span class="btn btn-success fileinput-button">
            <i class="glyphicon glyphicon-plus"></i>
            <span>Add files...</span>
        </span>
        <button type="submit" class="btn btn-primary start">
            <i class="glyphicon glyphicon-upload"></i>
            <span>Start upload</span>
        </button>
        <button type="reset" class="btn btn-warning cancel">
            <i class="glyphicon glyphicon-ban-circle"></i>
            <span>Cancel upload</span>
        </button>
      </div>
      <div class="col-lg-5">
        <!-- The global file processing state -->
        <span class="fileupload-process">
          <div id="total-progress" class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
            <div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
          </div>
        </span>
      </div>
    </div>
<!-- HTML heavily inspired by http://blueimp.github.io/jQuery-File-Upload/ -->
<div class="table table-striped" class="files" id="previews">
  <div id="template" class="file-row">
    <!-- This is used as the file preview template -->
    <div>
        <span class="preview"><img data-dz-thumbnail /></span>
    </div>
    <div>
        <p class="name" data-dz-name></p>
        <strong class="error text-danger" data-dz-errormessage></strong>
    </div>
    <div>
        <p class="size" data-dz-size></p>
        <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
          <div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
        </div>
    </div>
    <div>
      <button class="btn btn-primary start">
          <i class="glyphicon glyphicon-upload"></i>
          <span>Start</span>
      </button>
      <button data-dz-remove class="btn btn-warning cancel">
          <i class="glyphicon glyphicon-ban-circle"></i>
          <span>Cancel</span>
      </button>
      <button data-dz-remove class="btn btn-danger delete">
        <i class="glyphicon glyphicon-trash"></i>
        <span>Delete</span>
      </button>
    </div>
  </div>
</div>

dialog = $( "#dialog" ).dialog({
  autoOpen: false,
  height: 400,
  width: 900,
  modal: true,
});
$(function(){
var uniqId;
$( ".btn" ).button().on( "click", function() {
    dialog.dialog( "open" );
    uniqId = $(this).attr('data-id');
});
var previewNode = document.querySelector("#template");
previewNode.id = "";
var previewTemplate = previewNode.parentNode.innerHTML;
previewNode.parentNode.removeChild(previewNode);
var myDropzone = new Dropzone(document.body, { // Make the whole body a dropzone
  url: "/target-url", // Set the url
  thumbnailWidth: 80,
  thumbnailHeight: 80,
  parallelUploads: 20,
  previewTemplate: previewTemplate,
  autoQueue: false, // Make sure the files aren't queued until manually added
  previewsContainer: "#previews", // Define the container to display the previews
  clickable: ".fileinput-button", // Define the element that should be used as click trigger to select files.
  params: {
    uniq: uniqId // Возвращает undefined
  }
});
myDropzone.on("addedfile", function(file) {
  // Hookup the start button
  file.previewElement.querySelector(".start").onclick = function() { myDropzone.enqueueFile(file); };
});
// Update the total progress bar
myDropzone.on("totaluploadprogress", function(progress) {
  document.querySelector("#total-progress .progress-bar").style.width = progress + "%";
});
myDropzone.on("sending", function(file) {
  // Show the total progress bar when upload starts
  document.querySelector("#total-progress").style.opacity = "1";
  // And disable the start button
  file.previewElement.querySelector(".start").setAttribute("disabled", "disabled");
});
// Hide the total progress bar when nothing's uploading anymore
myDropzone.on("queuecomplete", function(progress) {
  document.querySelector("#total-progress").style.opacity = "0";
});
// Setup the buttons for all transfers
// The "add files" button doesn't need to be setup because the config
// `clickable` has already been specified.
document.querySelector("#actions .start").onclick = function() {
  myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED));
};
document.querySelector("#actions .cancel").onclick = function() {
  myDropzone.removeAllFiles(true);
};

});

При нажатии кнопок Btn1, Btn2 открывается модальное окно, в котором поля для загрузки файлов, необходимо вытащить из кнопки атрибут data-id и отправить его в свойство params объекта myDropzone... В моем способе он возвращает undefined

Answer 1

у вас uniqId получает значение при клике на кнопку в

$( ".btn" ).button().on( "click", function() {
    dialog.dialog( "open" );
    uniqId = $(this).attr('data-id');
    // Остальную часть сюда
});

Попробуйте добавить ваш код, и остальные зависимости при действие click

READ ALSO
Фильтр по категориям JS, VueJS

Фильтр по категориям JS, VueJS

Подскажите как сделать фильтр по категориямЧтобы при выборе категории, отображались элементы только с этой категории

237
получение точек с карты вне iframe

получение точек с карты вне iframe

есть карта https://wwwgoogle

182
Ответ ajax комментируется в html файле

Ответ ajax комментируется в html файле

Всем приветПишу запрос ajax на js через POST

174
Излишнее данные после сборки js/css с помощью webpack в файле назначения

Излишнее данные после сборки js/css с помощью webpack в файле назначения

Я провожу сборку js/css с помощью webpack в окружении development (те

221