选择文件时自动提交上传表单,并触发操作

Jes*_*ica 0 html javascript forms jquery

我试图在用户上传文件时自动提交上传的文件。我发现的最短方法是插入onChange="form.submit()"上传文件inputSource我这样做了,现在当我向submit input(通过 JavaScript)插入一个动作时,它不会被触发。

执行时如何触发事件onChange="form.submit()"

JSFiddle

代码片段:

$("form").on('submit',function(){
    alert("It works");
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="http://example.com">
    <input type="file" id="file" onChange="form.submit()" />
    <input id="submit" type="submit" name="submit" value="Upload"/>
</form>
Run Code Online (Sandbox Code Playgroud)

更新

我知道可以使用 .$('#file').change(function()...但我想知道是否可以使用onChange="form.submit()".

AiA*_*aec 5

解决方案1:jsFiddle 1

$(document).ready(function(){
    $("form").on('submit',function(){
        alert("It works");
    });
});
Run Code Online (Sandbox Code Playgroud)
<form action="http://example.com">
    <input type="file" id="file" onchange="$('form').submit();" />
    <input id="submit" type="submit" name="submit" value="Upload"/>
</form>
Run Code Online (Sandbox Code Playgroud)

解决方案 2:jsFiddle 2

$(document).ready(function(){
    $("form").on('submit',function(){
        alert("It works");
    });
});

function submitForm()
{
    $('form').submit();
}
Run Code Online (Sandbox Code Playgroud)
<form action="http://example.com">
    <input type="file" id="file" onchange="submitForm()" />
    <input id="submit" type="submit" name="submit" value="Upload"/>
</form>
Run Code Online (Sandbox Code Playgroud)