2014-07-05 116 views
2

我想在我的應用程序中使用圖像作爲文件類型按鈕,但點擊圖像功能正在執行,但按鈕document.getElementById("myFile").click();未執行。我的代碼有什麼問題?問題點擊事件

HTML:

<div align="center"> 
     <a href="#" id="other-color" onClick='loadFile()'><img style="width:75px;height:auto" src="icons/slr-camera-2-256.png"/></a> 
     <input type="file" id="myFile" style="display:none" /> 
    </div> 

腳本:

function loadFile() 
     { 

      alert("test"); 
      document.getElementById("myFile").click(); 
     } 
+0

同時取出'html5'和'jQuery'標籤,因爲這個問題不有 –

+0

你的代碼適合我!它應該是別的 – Konst

+0

@Precious如果使用jQuery是可以接受的,請添加標籤。你可以嘗試使用jQuery來選擇元素,如:$('#myFile')。click()' – Kabie

回答

0

檢查該解決方案(SpYk3HHJsFiddle或者您可以使用以下方法:

$('#myFile').show(); 
$('#myFile').focus(); 
$('#myFile').click(); 
$('#myFile').hide(); 

Florin Mogos的想法是讓它們在點擊事件之前可見和集中。

1

你可以嘗試這樣的,使用JQuery:

<input type="file" id="FileInput" style="display: none"/> 
<img src="abc.png" id="UploadPic" style="cursor: pointer;" /> 

和jQuery:

<script type="text/javascript"> 
    $(document).ready(function(){ 
     $("#FileInput").change(function() { 
     $("#UploadPic").click(); 
    }); 
    }); 
</script> 
0

爲了保持安全,請將您的JS從HTML中分離出來。你不是第一個遇到嵌入在HTML中的JS事件的問題。我發現這兩個問題分開時最好解決。

下面是他們分開時的版本。

DEMO

HTML

<div align="center"> <a href="#" id="other-color"><img style="width:75px;height:auto" src="icons/slr-camera-2-256.png"/></a> 

    <input type="file" id="myFile" style="display:none" /> 
</div> 

JS

var a = document.getElementById('other-color'); 
a.onclick = loadFile; 

function loadFile() { 
    alert("test"); 
} 
0

使用觸發

HTML

<div align="center"> 
    <a href="javascript:void(0);" id="other-color"><img style="width:75px;height:auto" src="icons/slr-camera-2-256.png"/></a> 
    <input type="file" id="myFile" style="display:none" /> 
</div> 

jQuery的

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
    $('#other-color').click(function(){ 
     $('#myFile').trigger('click'); 
    }); 
}); 
</script>