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

多个输入文件元素上的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)

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题