【问题标题】:JQuery change Event Issue When Same File select选择相同文件时的JQuery更改事件问题
【发布时间】:2015-12-29 03:15:46
【问题描述】:

我使用 jQuery 的 change 事件从我的计算机中捕获选择的图像。

$("#user_photo").change(function () {
  alert('yes');
}); 

但我的问题是当我再次选择相同的文件时,此功能不起作用。是的,显然不会。但我想要一个解决方案。你能帮帮我吗?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    这种行为在所有浏览器上并不相同。例如在firefox上使用以下代码sn-p,即使您选择相同的文件,您也会收到警报。

    $('#test').on('change', function() {
      alert('yes');  
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input id="test" type="file" />

    但你可能会很棘手。您可以使用输入文件,当上传文件时,将其放在您的服务器上,销毁输入文件并重新创建一个新的输入文件。但是如果你想这样做,你必须决定如何在你的服务器上上传文件,因为不是每个浏览器都有 javascript FileAPI。这是一个例子:

    $(document.body).on('change', '#test', function() {
      // Upload the file on your servlet, i can't really do the code for that. You case use the FileAPI or a library for that. Just take care of browsers compatibility : http://caniuse.com/#feat=fileapi
      
      // When the file is uploaded
      alert('yes');
      
      // Replace the input by a new one
      $(this).replaceWith('<input id="test" type="file">');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input id="test" type="file" />

    当然,您可以通过显示上传的文件来改进此代码。

    【讨论】:

    • 实际上,当用户选择图像然后可以裁剪它时,我正在打开一个模式。如果用户在模型中单击,但如果用户想要再次思考并想要裁剪不同的轴,则会导致问题。我希望你明白这一点。
    • @ArP:您可以将上述技术应用于该场景。
    【解决方案2】:

    在事件中使用,像这样

    $("#user_photo").on("change", function () {
      alert('yes');
    }); 
    

    或者如果元素是动态添加的,可以使用以下

    $("body").on("change", "#user_photo", function () {
       alert('yes');
    });
    

    【讨论】:

      猜你喜欢
      • 2013-03-05
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      • 2012-08-20
      • 2010-11-30
      相关资源
      最近更新 更多