2014-12-13 53 views
0

我有多个输入类型的文件。默认情况下,它们是隐藏的,只显示第一个。当用户使用第一个输入文件选择文件时,下面的功能按ID显示下一个输入类型文件。问题是,它仅适用于前2个更改事件,并且不会停止而没有错误。我如何使它适用于每个下一个输入文件。下面是函数:Jquery输入类型文件作为触发器不起作用

//first we hide all inputs 
$('.imagediv').hide(); 
$('.imagediv:first').show(); 
var nextupload=$('.imagediv:first').attr('data'); 
nextupload=(parseInt(nextupload) + 1); 

//this is the event 
$(function() { 
$("input:file").change(function(){ 
    var nextf = $(this).attr('data'); 
    $('#input'+(nextupload)+'').show(); 
    alert('#input'+(nextupload)+''); 
});  
}); 

这里是HTML的样子:

<div class="imagediv" id="input2" data="2"> 
<input type="file" name="gallery_upload_2" data="gallery_upload_3" id="gallery_upload_2" /> 
</div> 

等下一个输入.. 如何使之成为每一个输入的变化工作?由于

我做的jsfiddle这里:http://jsfiddle.net/Lbu3ksjh/1/

+0

$( “输入:文件”),而不是该使用$( “#gallery_upload_2”) – 2014-12-13 13:03:39

+0

会出现什么这个改变?我不会错过这个事件,它触发与$(“输入:文件”),但只有2次:) – Europeuser 2014-12-13 13:06:16

回答

2

你失踪的变化,功能+1部分:

$('input:file').change(function(){ 
    var nextupload = $(this).parent('.imagediv').attr('data'); 
    nextupload = (parseInt(nextupload) + 1); 
    $('#input'+(nextupload)+'').show(); 
    alert('#input'+(nextupload)+''); 
}); 

我更新了你的提琴:

Demo

+0

经验丰富,谢谢,我成功与我这个自我:$(function(){ $('。imagediv ').hide(); $('。imagediv:first')。show(); $(“input:file”)。change(function(){ var nextf = $(this).attr('数据'); \t $('#input'+(nextf)+'')。next()。show(); }); });但斯蒂尔我会投票并接受你的回答,谢谢! – Europeuser 2014-12-13 13:27:36

+0

谢谢,不客气。 – empiric 2014-12-13 13:29:11

2

这是另一种解决方案。它适用于可变数量的文件输入,不需要大量代码或标记。

DEMO

JS

$(function() { 
    var $fileInputs = $(':file[name*="gallery_"]'), // could be whatever 
     next = 0; 

    $fileInputs.not(':first').hide(); 

    $fileInputs.change(function(){ 
     $fileInputs.eq(++next).show(); 
    }); 
}); 

HTML

<input type="file" name="gallery_upload_1" /> 
<input type="file" name="gallery_upload_2" /> 
<input type="file" name="gallery_upload_3" /> 
<input type="text" name="random_text_input" /> 
<!-- notice it only reveals file inputs --> 
<input type="file" name="gallery_upload_4" />