jquery 从模态窗口获取带有属性的数据

tcomlyy6  于 2023-06-22  发布在  jQuery
关注(0)|答案(3)|浏览(143)

我有一个用于上传文件的模态窗口,它在这段代码中使用

<div class="field">
    <label>Photos</label>
    <div class="field_info" data-field_photo_id="5">
        <div class="value" data-item_id=""></div>
    </div>
    <div class="field_form">
        <a class="btn btn-dark btn-md btnUpload" data-toggle="modal" href="#" data-target="#modal-upload">
            <i class="fa fa-cloud-upload"></i> Upload
        </a>
        <div class="dz_params_item"
          data-entity_id="<?=$item->request_id?>"
          data-action_url="/files/upload/<?=$item->request_id?>"
        ></div>
    </div>
</div>

窗口本身在页面上的位置稍低一些

<div class="modal fade" id="modal-upload" tabindex="-1" role="dialog" aria-hidden="true">
    ....
</div>

要打开它并上传文件,我使用JavaScript
我已经缩短了代码一点无处不在,使没有混乱,但如果有什么是失踪,那么我将补充

(function( $ ){
    $.dispatcherFiles = {
        $filesDropzone: null,
        $parallelUploads: 100,
        $maxFiles: 10,
        $modalId: '#modal-upload',
        $files: [],

        cacheDom: function(){
            this.$body = $('body');
        },

        functions: {
            openUploadFilesModal: function (e) {
                let that = this;

                let dropzoneParamEl = $(e.currentTarget).closest('.field_form').find('.dz_params_item');
                let action_url = $(dropzoneParamEl).attr('data-action_url');          

                $(this.$modalId + ' #filesDropzone').addClass('dropzone');

                this.$filesDropzone = new Dropzone(that.$modalId + ' .dropzone', {
                    url: action_url,
                    uploadMultiple: true,
                    parallelUploads: that.$parallelUploads,
                    maxFiles: that.$maxFiles,
                });
            },

            hideUploadFilesModal: function (e) {
                this.$filesDropzone.destroy();
            },
        },

        events: function(){
            this.$body.on('shown.bs.modal', this.$modalId, this.functions.openUploadFilesModal.bind(this));
            this.$body.on('hidden.bs.modal', this.$modalId, this.functions.hideUploadFilesModal.bind(this));
        },

        init: function () {
            this.cacheDom();
            this.events();
        }
    };

    $.dispatcherFiles.init();

})(jQuery);

因此,在本例中,我遇到的主要问题是从html页面获取data-action_url
我正在用这些线条来做

let dropzoneParamEl = $(e.currentTarget).closest('.field_form').find('.dz_params_item');
let action_url = $(dropzoneParamEl).attr('data-action_url');

但是最后我的变量是undefined,尽管前面的变量dropzoneParamEl已经定义,并且我得到了该元素的DOM
而这一切都只是因为我的函数是在窗口打开时触发的shown.bs.modal
如果我通过click接收数据,那么我可以获得所需的属性
但据我所知,我不能使用click模式来打开,因为那样的话什么都不起作用
在这种情况下,如何在打开模态时获得data-action_url的值?我马上澄清,我可以有几个这样的上传按钮,我需要的值正是被点击的元素

更新

也就是说,我可以简单地用这个函数替换事件中的两个函数

events: function(){
            this.$body.on('click', '#foo', this.functions.uploadFilesModal.bind(this));
        },

在那里做我该做的事?

functions: {
            uploadFilesModal: function (e) {
                $($modalId).modal('toggle');

                let that = this;

                let dropzoneParamEl = $(e.currentTarget).closest('.field_form').find('.dz_params_item');
                let action_url = $(dropzoneParamEl).attr('data-action_url');
                
                console.log(dropzoneParamEl);
                console.log(action_url);

                ...
            },
        },

=====================================
我试图做一个近似的片段,但不幸的是什么都没有打开。

(function($){
    let $modalId = '#modal-upload';
    let $filesDropzone = null;
    let $parallelUploads = 100;
    let $maxFiles = 10;
    let $files = [];
        
    $.dispatcherFiles = {

        cacheDom: function(){
            this.$body = $('body');
        },

        functions: {
            uploadFilesModal: function (e) {
                $($modalId).modal('toggle');
                
                let that = this;

                let dropzoneParamEl = $(e.currentTarget).closest('.field_form').find('.dz_params_item');
                let action_url = $(dropzoneParamEl).attr('data-action_url');
                
                console.log(dropzoneParamEl);
                console.log(action_url);

                $($modalId + ' #filesDropzone').addClass('dropzone');

                $filesDropzone = new Dropzone($modalId + ' .dropzone', {
                    url: action_url,
                    uploadMultiple: true,
                    parallelUploads: $parallelUploads,
                    maxFiles: $maxFiles,
                });
                
                $filesDropzone.on('error', function() {
                    $(that.$modalId).modal('hide');
                    alert('error');
                });
                
                $filesDropzone.on('success', function(file, response) {
                    $($modalId).modal('hide');
                });
            },
        },

        events: function(){
            this.$body.on('click', '.btnUpload', this.functions.uploadFilesModal.bind(this));
        },

        init: function () {
            this.cacheDom();
            this.events();
        }
    };

    $.dispatcherFiles.init();

})(jQuery);
.field {
  margin: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" integrity="sha512-t4GWSVZO1eC8BM339Xd7Uphw5s17a86tIZIj8qRxhnKub6WoyhnrxeCIMeAqBPgdZGlCcG2PrZjMc+Wr78+5Xg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" 
  rel="stylesheet"  type='text/css'>

<div class="form-group">
  <div class="field">
      <label>Photos</label>
      <div class="field_info" data-field_photo_id="5">
          <div class="value" data-item_id=""></div>
      </div>
      <div class="field_form">
          <a class="btn btn-dark btn-md btnUpload" data-toggle="modal" href="#" data-target="#modal-upload">
              <i class="fa fa-cloud-upload"></i> Upload
          </a>
          <div class="dz_params_item"
            data-entity_id="<?=$item->request_id?>"
            data-action_url="/files/upload/<?=$item->request_id?>"
          ></div>
      </div>
  </div>
</div>

<div class="form-group">
  <div class="field">
      <label>Photos</label>
      <div class="field_info" data-field_photo_id="6">
          <div class="value" data-item_id=""></div>
      </div>
      <div class="field_form">
          <a class="btn btn-dark btn-md btnUpload" data-toggle="modal" href="#" data-target="#modal-upload">
              <i class="fa fa-cloud-upload"></i> Upload
          </a>
          <div class="dz_params_item"
            data-entity_id="<?=$item->request_id?>"
            data-action_url="/files/upload/<?=$item->request_id?>"
          ></div>
      </div>
  </div>
</div>

<div class="form-group">
  <div class="field">
      <label>Photos</label>
      <div class="field_info" data-field_photo_id="7">
          <div class="value" data-item_id=""></div>
      </div>
      <div class="field_form">
          <a class="btn btn-dark btn-md btnUpload" data-toggle="modal" href="#" data-target="#modal-upload">
              <i class="fa fa-cloud-upload"></i> Upload
          </a>
          <div class="dz_params_item"
            data-entity_id="<?=$item->request_id?>"
            data-action_url="/files/upload/<?=$item->request_id?>"
          ></div>
      </div>
  </div>
</div>

<div class="modal fade" id="modal-upload" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    Upload files
                </h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true"><i class="fal fa-times"></i></span>
                </button>
            </div>
            <div class="modal-body">
                <div id="filesDropzone"></div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.min.js" integrity="sha512-3dZ9wIrMMij8rOH7X3kLfXAzwtcHpuYpEgQg1OA4QAob1e81H8ntUQmQm3pBudqIoySO5j0tHN4ENzA6+n2r4w==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.min.js" integrity="sha512-U2WE1ktpMTuRBPoCFDzomoIorbOyUv0sP8B+INA3EzNAhehbzED1rOJg6bCqPf/Tuposxb5ja/MAUnC8THSbLQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
bbmckpt7

bbmckpt71#

你可以调用$($modalId).modal('toggle');,见下面的代码片段:

(function($){
    let $modalId = '#modal-upload';
    let $filesDropzone = null;
    let $parallelUploads = 100;
    let $maxFiles = 10;
    let $files = [];
    

    $("#foo").click(function() {
        $($modalId).modal('toggle');
    });

})(jQuery);
.field {
  margin: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" integrity="sha512-t4GWSVZO1eC8BM339Xd7Uphw5s17a86tIZIj8qRxhnKub6WoyhnrxeCIMeAqBPgdZGlCcG2PrZjMc+Wr78+5Xg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" 
  rel="stylesheet"  type='text/css'>

<div class="field">
    <label>Photos</label>
    <div class="field_info" data-field_photo_id="5">
        <div class="value" data-item_id=""></div>
    </div>
    <div class="field_form">
        <a class="btn btn-dark btn-md btnUpload" data-toggle="modal" href="#" data-target="#modal-upload" id="foo">
            <i class="fa fa-cloud-upload"></i> Upload
        </a>
        <div class="dz_params_item"
          data-entity_id="<?=$item->request_id?>"
          data-action_url="/files/upload/<?=$item->request_id?>"
        ></div>
    </div>
</div>

<div class="modal fade" id="modal-upload" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">
                    Upload files
                </h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true"><i class="fal fa-times"></i></span>
                </button>
            </div>
            <div class="modal-body">
                <div id="filesDropzone"></div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.min.js" integrity="sha512-3dZ9wIrMMij8rOH7X3kLfXAzwtcHpuYpEgQg1OA4QAob1e81H8ntUQmQm3pBudqIoySO5j0tHN4ENzA6+n2r4w==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
bpzcxfmw

bpzcxfmw2#

我认为你可以将on("click")和内置的HTML标签dialog一起使用。考虑它的docs
下面是一个没有任何样式的简短示例。希望能成功。如果用户取消“选择文件”对话框窗口,HTML对话框也会自动关闭。

$("#show").on("click", function() {
  document.getElementById("upload").showModal();
});

$("#upload").on("close", function() {
  if (this.returnValue === "cancel") {
    // User canceled the dialog
  } else if (this.returnValue === "submit") {
    var file = document.getElementById("file").files;
    // User submitted the dialog
    // Use the "item" method to retrieve File objects
    
    var target = $("#show").closest(".field_form").find(".dz_params_item");
    var url = target.attr("data-action_url");
    
    // What you do with "data-action_url"
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<dialog id="upload">
  <form>
    <!-- Add a style if you want -->
    <input type="file" id="file" />
    <!-- Anything else you'd like to be near the file input -->
    <br /><br />
    <div>
      <!-- Again, here might be a class or something -->
      <button value="cancel" formmethod="dialog">Cancel</button>
      <button value="submit" formmethod="dialog">Submit</button>
    </div>
  </form>
</dialog>

<button id="show">Upload</button>
nr9pn0ug

nr9pn0ug3#

如果您正在获取DOM对象或jQuery对象的示例,则执行此操作

let dropzoneParamEl = $(e.currentTarget).closest('.field_form').find('.dz_params_item');

我的意思是,dropzoneParamEl有你需要的DOM,然后使用以下代码:

let action_url = $(dropzoneParamEl).data('action_url');

我已经在jQuery中使用这个函数很长时间了。
也可以使用vanilla JavaScript查看'data'属性,使用:

let dropzoneParamEl = document.querySelector('.dz_params_item');

dropzoneParamEl.dataset.action_url

您必须更改代码以满足您的需要,但基本上您可以使用这两个选项获取数据

相关问题