【问题标题】:Jquery display value of input type file to other elementJquery 将输入类型文件的值显示给其他元素
【发布时间】:2013-10-10 07:12:19
【问题描述】:

我正在尝试向元素显示输入文件的值/名称。代码运行正常.. 但问题是当用户单击并选择一个文件时。该文件不会在用户选择文件的 时刻 显示,而是在用户再次单击上传按钮时显示。那么我将如何使输入字段的值在用户做出选择时显示出来。

$(document).ready(function () {
    $(".filename").each(function () {
        $('.upload').click(function () {
            $('#file_button').click();
            var file = $('#file_button').val();
            if (file !== null) {
                if ($('.filename').val() !== null) {
                    $($('.filename')).empty();
                }
                $('<span>' + file + '</span>').appendTo('.filename');
            }
        });
    });
});

我的 CSS :

#file_button {
   display: none;  
} 

//然后向下去css上传按钮

HTML:

<button type="button" class="upload"> Upload a File </button>
<p class="filename"> </p>
<input type="file" id="file_button"/> 

【问题讨论】:

  • onchange 事件绑定到输入。
  • $('#file_button').click();什么都不做
  • 怎么样..?抱歉忘了说我还是 jquery 的新手 @Nilotpal Barpujari
  • if(file !== null){ if($('.filename').val() !== null){ 看起来你真的很想确定。猜猜什么值永远不会为空。 ;)

标签: javascript jquery html css


【解决方案1】:

检查这个...

Demo Fiddle

$(document).ready(function () {
    $(".filename").each(function () {
        $('.upload').click(function () {
            $('#file_button').click();

        });

        $("#file_button").change(function () {
            var file = $('#file_button').val();
            if (file !== null) {
                if ($('.filename').val() !== null) {
                    $($('.filename')).empty();
                }
                $('<span>' + file + '</span>').appendTo('.filename');
            }
        });
    });
});

【讨论】:

    【解决方案2】:
    $("#file_button").on('change',function(){
        alert('Selected');
    });
    

    然后确实希望通过替换警报来达到您的预期。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多