2017-09-23 14 views
0

動態輸入文件中的字段都被選擇的文件名我也可以更通過點擊添加動態輸入型文件中的字段添加更多使用jQuery/JavaScript的

我已經腳本時選擇它來獲取文件名,但它只爲第一個領域而不是其他領域。

那麼如何在選擇時獲取所有文件名?

$("#em_add").click(function(){ 
 
\t \t \t var decoration_box = $(".one").html(); 
 
\t \t \t $(".logos").append('<div class="one">'+decoration_box+'</div>'); 
 
}); 
 

 
$('.logo').change(function() { 
 
\t var filePath=$(this).val(); 
 
\t alert(filePath); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="em_add">Add New</button> 
 
<div class="logos"> 
 

 
    <div class="one"> 
 
    <input type="file" name="logo[]" id="logo" class="logo" /> 
 
    </div> 
 
    
 
</div>

回答

1

要動態添加的元素,但是當你添加你不重視的事件處理程序對這些新的元素。要解決此問題,您可以使用事件委派,將事件附加到父項.logos

$("#em_add").click(function(){ 
 
\t \t \t var decoration_box = $(".one").html(); 
 
\t \t \t $(".logos").append('<div class="one">'+decoration_box+'</div>'); 
 
}); 
 

 
$('.logos').on('change', '.logo', function() { 
 
\t var filePath=$(this).val(); 
 
\t alert(filePath); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="em_add">Add New</button> 
 
<div class="logos"> 
 

 
    <div class="one"> 
 
    <input type="file" name="logo[]" id="logo" class="logo" /> 
 
    </div> 
 
    
 
</div>

1

參考Jquery .on('change') not firing for dynamically added elements

$("#em_add").click(function(){ 
 
\t \t \t var decoration_box = $(".one").html(); 
 
\t \t \t $(".logos").append('<div class="one">'+decoration_box+'</div>'); 
 
}); 
 

 
$('.logos').on('change', 'input:file', function() { 
 
\t var filePath=$(this).val(); 
 
\t alert(filePath); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="em_add">Add New</button> 
 
<div class="logos"> 
 

 
    <div class="one"> 
 
    <input type="file" name="logo[]" id="logo" class="logo" /> 
 
    </div> 
 
    
 
</div>