【问题标题】:execute a javascript function when user selects a file当用户选择文件时执行 javascript 函数
【发布时间】:2012-05-11 08:57:31
【问题描述】:

在一个 html 页面中,我正在添加一个输入元素。

<input type="file" name="fileselect" id="fselect"> </input>

当用户选择一个文件时,我想执行一个 javascript 函数。假设我也想写入控制台。

jquery select() 是检查用户是否选择了文件的正确函数吗?我试过这样

$(document).ready(function(){
   $('#fselect').select(function(){ 
      console.log('selected');
      myfun(); 
    });
});

function myfun(){
   alert('you selected a file');
}

由于某种原因,当我使用输入元素选择文件时,没有任何内容写入控制台,也没有出现警告框。select() 调用编码错误吗?

【问题讨论】:

    标签: javascript file input


    【解决方案1】:

    你可以使用change事件:

    ​$("#fselect").change(function() {
        // do something
    });​​​​​​​
    

    演示: http://jsfiddle.net/BtsHL/

    【讨论】:

      【解决方案2】:

      你想要的事件是change,而不是select

      来自the docs

      当用户在其中进行文本选择时,选择事件会发送到元素。

      对于change

      当元素值改变时,改变事件被发送到元素

      【讨论】:

        【解决方案3】:

        试试这个:

        $(document).ready(function(){
           $('#fselect').change(function(){ 
              console.log('selected');
            });
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-26
          • 1970-01-01
          • 2015-04-30
          • 1970-01-01
          • 2019-09-10
          相关资源
          最近更新 更多