Привет. Клонирование не работает на измененном изображении

#javascript #html

Вопрос:

*Это простая таблица, в которую вводятся данные и есть кнопки для клонирования и удаления.

Моя проблема в том, что в клонированной строке изображение вообще не клонируется. образ, который я хочу изменить, не меняется. В частности, перед клонированием изображение изменяется, после клонирования оба изображения не изменяются. Я думаю, что входные данные не клонированы

Как это сделать??? Большое спасибо!.*

 $(document).ready(function($) {

  $(document).on('click', ".btn_row_below_new", function(e) {
    var r = $(this).closest('tr').clone();

    $.each(r.find('td'), function(i1, v1) {
      //clear all data / value in td / cell
      $(this).html('');
    });

    $(this).closest('tr').after(r);
  });
  //--->current line> new> end


  //--->current line> clone> start
  $(document).on('click', ".btn_row_below_clone", function(e) {
    var r = $(this).closest('tr').clone();
    $(this).closest('tr').after(r);
  });
  //--->current line> clone> end

  //--->current line> delete> start
  $(document).on('click', ".btn_row_delete", function(e) {
    var r = $(this).closest('tr').remove();
  });
  //--->current line> delete> end

});

function previewImage() {
  var file = document.getElementById("file").files;
  if (file.length > 0) {
    var fileReader = new FileReader();

    fileReader.onload = function(event) {
      document.getElementById("preview").setAttribute("src", event.target.result);
    };
    fileReader.readAsDataURL(file[0]);
  }
} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">

<div style="padding-left: 50px;padding-right: 50px;padding-top:100px;" class="container">
  <table class="table table-dark table-striped table-hover tbl_code_with_mark">
    <tr>
      <th>Foto</th>
      <th>Nome</th>
      <th>Descrizione</th>
      <th>Categoria</th>
      <th>Prezzo (€)</th>
      <th>Opzione
        <th>
    </tr>

    <tr>
      <td>
        <div>

          <img id="preview" src="https://d1muf25xaso8hp.cloudfront.net/https://s3.amazonaws.com/appforest_uf/f1595928150631x625876263392768800/foodimage.png?w=64amp;amp;h=64amp;amp;auto=compressamp;amp;dpr=1.25amp;amp;fit=max" style="display: block; margin: 0px; width: 100%; height: 50px; border-radius: 0px;">
          <input type="file" name="file" id="file" accept="image/*" onchange="previewImage();" style="opacity: 0;position: absolute;z-index: 15;cursor: pointer;left: 158px;width: 77px;height: 55px;top: 152px;">
        </div>
      </td>
      <td><textarea data-gramm_editor="false" tabindex="49" placeholder="" maxlength="" rows="1"></textarea></td>
      <td><textarea data-gramm_editor="false" tabindex="49" placeholder="" maxlength="" rows="1"></textarea></td>


      <td>
        <select>
          <option class="dropdown-choice dropdown-placeholder" value="amp;quot;PLACEHOLDER_1427118222253amp;quot;" disabled="" style="color: rgb(107, 107, 107); display: none;">Tutte le categorie</option>
          <option class="dropdown-choice" value="amp;quot;BLANK_1427118194589amp;quot;" style="color: rgb(107, 107, 107);"></option>
          <option class="dropdown-choice" value="amp;quot;fast_foodamp;quot;" style="color: rgb(107, 107, 107);">Agroalimentare</option>
          <option class="dropdown-choice" value="amp;quot;healthy_foodamp;quot;" style="color: rgb(107, 107, 107);">Aziende agricole olearie</option>
          <option class="dropdown-choice" value="amp;quot;traditional_foodamp;quot;" style="color: rgb(107, 107, 107);">Aziende agricole vitivinicole</option>
          <option class="dropdown-choice" value="amp;quot;hamburgeramp;quot;" style="color: rgb(107, 107, 107);">Aziende transf. agroalimentare</option>
          <option class="dropdown-choice" value="amp;quot;pizzaamp;quot;" style="color: rgb(107, 107, 107);">Caseifici</option>
          <option class="dropdown-choice" value="amp;quot;french_friseamp;quot;" style="color: rgb(107, 107, 107);">Lavorazione funghi e tartufi</option>
          <option class="dropdown-choice" value="amp;quot;sandwichamp;quot;" style="color: rgb(107, 107, 107);">Macellerie, pescherie, negozi tipici</option>
          <option class="dropdown-choice" value="amp;quot;coffeeamp;quot;" style="color: rgb(107, 107, 107);">Torrefazioni, industrie caffè</option>
          <option class="dropdown-choice" value="amp;quot;dessertamp;quot;" style="color: rgb(107, 107, 107);">Dessert</option>

        </select>
      </td>

      <td>
        <input type="number" tabindex="51" placeholder="" maxlength="">
      </td>

      <td>
        <span class="btn btn-sm btn-success btn_row_below_clone">Clona</span> |
        <span class="btn btn-sm btn-danger btn_row_delete">Elimina</span>
      </td>
    </tr>

  </table>
</div> 

Комментарии:

1. Я не понимаю проблемы, при клонировании строки изображение одно и то же?

2. строка клонирована, проблема в том, что изображение клонированной строки не заставляет меня ее изменять

3. Проблема в том, что вы используете ввод файла с абсолютным расположением под изображением для запуска загрузки файла. Поскольку он абсолютно расположен с одинаковым верхним и левым значением, входные данные для загрузки обоих файлов находятся под первым изображением. Вместо этого вы могли бы использовать относительное позиционирование. Однако я бы предложил использовать метки ввода для ссылки на правильный ввод, чтобы предотвратить ошибки при изменении размеров.

4. Кроме того, вы не можете выбрать идентификатор для клонированных элементов, если не убедитесь, что у них есть уникальный идентификатор. Идентификатор должен быть уникальным в соответствии со спецификацией html.

5. Если мой ответ полностью решает вашу проблему, пожалуйста, примите его (отметьте галочкой слева от ответа) как правильный ответ, чтобы другие люди могли видеть, что вам не нужна дополнительная помощь.

Ответ №1:

Я удалил большинство столбцов css и таблиц, которые не имеют отношения к вашему вопросу.

Я изменил ваш код предварительного просмотра, чтобы он был нацелен на правильный код, и добавил обработчик щелчка на изображении для правильного ввода файла. Это решение должно сработать для вас.

 $(document).ready(function($) {

  $(document).on('click', '.btn_row_below_clone', function(e) {
    var r = $(this).closest('tr').clone();
    $(this).closest('tr').after(r);
  });

  $(document).on('click', '.btn_row_delete', function(e) {
    var r = $(this).closest('tr').remove();
  });

  //Added click function when you click the image the file upload click event handler is triggered.
  $(document).on('click', 'img.preview', function(e) {
    $(this).closest('tr').find('.img-file').trigger('click');
  });

  //Changed the change handler of the file input so it targets the correct row.
  $(document).on('change', '.img-file', function(e) {
    var file = this.files;
    if (file.length > 0) {
      var target = $(this).closest('tr').find('.preview');
      var fileReader = new FileReader();
      fileReader.onload = function(event) {
        target.attr("src", event.target.result);
      };
      fileReader.readAsDataURL(file[0]);
    }
  });

}); 
 img.preview {
  height: 50px;
  width: 50px;
}

.img-file {
  display: none;
} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">

<div style="padding-left: 50px;padding-right: 50px;padding-top:100px;" class="container">
  <table class="table table-dark table-striped table-hover tbl_code_with_mark">
    <tr>
      <th>Foto</th>
      <th>Opzione</th>
    </tr>

    <tr>
      <td>
        <div>
          <img class="preview" src="https://d1muf25xaso8hp.cloudfront.net/https://s3.amazonaws.com/appforest_uf/f1595928150631x625876263392768800/foodimage.png?w=64amp;amp;h=64amp;amp;auto=compressamp;amp;dpr=1.25amp;amp;fit=max">
          <input type="file" name="file" class="img-file" accept="image/*">
        </div>
      </td>

      <td>
        <span class="btn btn-sm btn-success btn_row_below_clone">Clona</span> |
        <span class="btn btn-sm btn-danger btn_row_delete">Elimina</span>
      </td>
    </tr>

  </table>
</div>