【问题标题】:The button does not respond when dynamically loaded动态加载时按钮不响应
【发布时间】:2018-03-19 12:49:09
【问题描述】:

我写了一个脚本来上传文件到服务器。如果输入和标签永久是文档的一部分,则没有问题 - 一切正常,抛出。当我使用 .html () 函数加载要动态上传的表单时出现问题

然后上传停止工作。可以看到,我是按照 $(document) .on("click", "element") 的方式来做的,但是给的不多。

我忘记了什么?我错过了什么吗?

$(".user-av").on("click", function(e) {

  $(".dialog-global").fadeIn("slow");
  $(".dialog-head").html("<p>Update avatar</p>");
  $(".dialog-content").html('<input type="file" class="set-av" /><a href="#" class="upload-av-btn orange-btn">Upload</a>');

  e.stopPropagation();

});

$(document).on("click", ".upload-av-btn", function(e) {

  var files = $(".set-av").prop("files")[0];
  var form = new FormData();
  form.append("file", files);

  $.ajax({
    url: "upload.php",
    dataType: "text",
    cache: false,
    contentType: false,
    processData: false,
    data: form,
    type: "post",
  }).done(function(response) {
    alert(response);
  });

  e.stopPropagation();

});
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【问题讨论】:

    标签: jquery ajax upload


    【解决方案1】:

    试试这个脚本。

    $(document).ready(function(){
    $(".user-av").on("click", function(e) {
    
      $(".dialog-global").fadeIn("slow");
      $(".dialog-head").html("<p>Update avatar</p>");
      $(".dialog-content").html('<input type="file" class="set-av" /><a href="#" class="upload-av-btn orange-btn">Upload</a>');
    
      e.stopPropagation();
    
    });
    
    $(document).on("click", ".dialog-content .upload-av-btn", function(e) {
      e.preventDefault();
      var files = $(".set-av").prop("files")[0];
      var form = new FormData();
      form.append("file", files);
    
      $.ajax({
        url: "upload.php",
        dataType: "text",
        cache: false,
        contentType: false,
        processData: false,
        data: form,
        type: "post",
      }).done(function(response) {
        alert(response);
      });
    
    });
    
    });
    

    【讨论】:

    • 我以前试过这个,不幸的是它不起作用。不知道这里是不是要从FormData下载数据?
    猜你喜欢
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多