簡體   English   中英

為什么在文件輸入上觸發單擊事件會同時在表單上觸發提交事件?

[英]Why triggering a click event on a file input will trigger also submit event on form?

我正在將HTML格式的文件輸入換膚。 我通過隱藏輸入實現了結果,然后設計了自己的按鈕並在該按鈕上單擊,在隱藏的輸入上觸發click事件,以打開本機瀏覽窗口。 這可行,但是當我關閉瀏覽窗口時,在表單上觸發了Javascript提交處理程序(但實際上並未發生任何提交,僅觸發了事件)。

我准備了一個小提琴: http : //jsfiddle.net/Ebcu5/

HTML:

<form id="form">
    <input id="file" type="file" name="photo" />
    <button id="upload">Browse</button>
</form>

JS:

$("#form").submit(function(){
    alert('submit event triggered');
});

document.getElementById('upload').addEventListener('click',function(){
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("click", true, true);
    uploading = true;
    document.getElementById('file').dispatchEvent(evt);
});

CSS:

input#file { position: fixed; top: -100px; }
button { border: solid 3px black; border-radius: 3px; font-size: 18px; line-height: 20px; text-transform: uppercase; font-family: Arial; line-height: 31px; background: #fd6706; border-radius: 13px; }

解決了。 只需在上載click事件處理程序中使用evt.preventDefault()。

更新的小提琴: http : //jsfiddle.net/Ebcu5/2/

document.getElementById('upload').addEventListener('click',function(evt){
                evt.preventDefault();
    document.getElementById('file').click();
});

更改: <button id="upload">Browse</button>

若要: <button id="upload" type="button">Browse</button>

值得稱贊的是Kevin B對另一個答案的評論:

或只是將按鈕變成按鈕。 type =“ button” – Kevin B 13年11月26日在22:35

只是希望它是一個實際的答案,所以人們會看到它而無需通過評論進行挖掘。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM