doushi1912 2018-01-02 14:25
浏览 268
已采纳

多个输入文件元素上的addEventListener

I have a foreach loop that provides me with multiple (about 5) file input elements.

I got the form to work with a simple submit button, but I would like to get it working without one too (upload when selected).

I get stuck trying to let Js or jQuery react to whichever button is clicked.

My php that provides the upload buttons:

<?php
  $getCampaign = new Crud();
  $query = "SELECT * FROM `table`";
  $aRow = $getCampaign->getData($query);

  if ($aRow == false){
    echo '<div class="alert alert-danger">No Campaigns!<br/></div>';
  } else { 
    foreach ($aRow as $row) {
      echo '<div class="row marginBottom">';
      echo '<div class="col-sm-2"><strong> '. $row['campaign'] .' </strong></div>';
      echo '<div class="col-sm-5"> '. $row['sort'] .'</div>';
      echo '<div class="col-sm-5">
        <form method="post" enctype="multipart/form-data"  action="process-upload-excel.php">
        <input type="file" id="' . $row['campaign'] . $row['sort'] .'" class="btn btn-primary btn-sm">
        <button type="submit" class="addfile">Upload File!</button>
      </form>';
      echo '</div></div>';
  }
<hr/>

  <div id="content">
      <div id="response"></div>
        <ul id="image-list">
        </ul>
  </div>

Start of js (what I got so far):

//Check for FormData
if (window.FormData) {
  formdata = new FormData();
  $(".addfile").css("display", "none");
}

???.addEventListener("change", function (evt) {
  document.getElementById("response").innerHTML = '<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i><span class="sr-only">Loading...</span>';
// rest of code checking name of file etc.
}

I got 'Campaign' and 'Sort' in a DB.

Out of these entries I create the input file elements. So people can upload the right file for the right Campaign.

But how do I use the addEvenListener the correct way for this example?

I hope someone can educate me.

Thanks in advance

  • 写回答

1条回答 默认 最新

  • douye6812 2018-01-02 15:23
    关注

    You can use delegate and do it like this:

    html

    <div id="content">
    
    </div>
    

    JS

    // Add two uploaders
    for (var i = 1; i <= 2; i++) {
      $('#content').append($('<input type="file" id="uploader' + i + '">'));
    }
    
    // Add listener for them
    $("#content").delegate("input[type=file]", "change", function() {
      alert($(this).attr("id"));
    });
    

    Online demo (Fiddle)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大