【问题标题】:jquery .change() method not working properlyjquery .change() 方法无法正常工作
【发布时间】:2014-04-27 12:46:01
【问题描述】:

我正在尝试上传文件。问题是当用户在选择文件之前单击提交按钮时,用户应该得到任何警报。如果文件已经被选择,submitbutton 的值应该更改为Updating... .为此我使用了change()方法,但它不能正常工作。

javascript文件:

    $(document).ready(function()
    { 
      var file_name='';
      //for checking whether the file queue contain files or not
      $('#upload').click(function()
      { 
       $('#file').live('change',function(){
           for (var i = 0; i < this.files.length; i++)
           {
           file_name =  this.files[i].name; 
           //alert(file_name); 
            if(file_name !== null && file_name !== undefined)
            {
                $('#upload').attr('value','Updating..');
            } 
            else
            {
                alert('error');
            }  
           }//end for loop
       }); 
    });
}); 

html:

<form id='file-form' action="" method="post" enctype="multipart/form-data"> 
<input type="file" name="file" id="file" ><br>
<input type="button" name="upload" id='upload' value="Upload file">
</form>

请帮帮我。

【问题讨论】:

  • change 事件处理程序放在上传click 事件处理程序之外。当您单击上传按钮时,您的事件change 将绑定处理程序。
  • .live 现在已弃用。使用 .on instaed
  • 它还没有工作。@samitha
  • 要检查队列是否包含文件,您可以检查属性值是否为空$('#file').attr("value") != ""
  • 你在控制台得到了什么?

标签: php jquery file


【解决方案1】:

根据 JQuery 文档,不推荐使用 .live 方法。

$('#file').on('change',function(){
       //your code
   }); 

试试这个

【讨论】:

    【解决方案2】:

    您已将 file_name 初始化为 ''。然而,在您的比较中,您正在检查它是否等于 null 或未定义,当未设置时,这两者都不是真的。

    代替:

    if(file_name !== null && file_name !== undefined)
    

    您可能正在寻找:

    if (file_name !== '')
    

    【讨论】:

      猜你喜欢
      • 2018-05-09
      • 2018-12-11
      • 1970-01-01
      • 2015-11-13
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      相关资源
      最近更新 更多