【问题标题】:how to prevent doubling the input file if the user opened it and closed it without choosing a file如果用户在没有选择文件的情况下打开并关闭它,如何防止输入文件加倍
【发布时间】:2019-09-02 14:14:31
【问题描述】:

我希望当用户选择一个文件时,会创建另一个输入文件,但是当用户打开它并关闭它而不选择文件时使用我的代码,然后他再次打开它并选择一个,如果他创建了 2 个输入打开和关闭 3 次,然后选择一个,创建了 4 个输入。 如果他从第一次选择一个文件,那么只会创建一个


<div class="gal-stf">
    <input class="plus-n" type="file">
      <p class="bt"></p>
  </div>
      <div class="ad-photo" style="display: none;">

      <div class="gal-stf">
    <input class="plus-n" type="file">
          <p></p>
  </div>
          </div>


$(".gal").on("click", ".plus-n", function () {

              var el = $(this).val();
              $(this).change(function () {
        $('.gal').append($('.ad-photo .gal-stf').last().clone(false));
                  $(this).prop('disabled' , 'disabled');
                  $(this).siblings('p').text(this.value);
      });
    });

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    实际上,这是因为您在每次点击时都绑定了事件处理程序,所以3 click 表示 3 个不同的处理程序,每个处理程序都会在更改事件发生时触发。使用事件委托而不是直接监听 click 事件来监听 change 事件。

    $(".gal").on("change", ".plus-n", function() {
      $('.gal').append($('.ad-photo .gal-stf').last().clone(false));
      $(this).prop('disabled', 'disabled');
      $(this).siblings('p').text(this.value);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="gal">
      <div class="gal-stf">
        <input class="plus-n" type="file">
        <p class="bt"></p>
      </div>
      <div class="ad-photo" style="display: none;">
    
        <div class="gal-stf">
          <input class="plus-n" type="file">
          <p></p>
        </div>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 2020-02-10
      • 1970-01-01
      相关资源
      最近更新 更多