0

I have this jquery script, and it does not work in head tag.

<script type="text/javascript">
    $(window).load(function() {
        $( "#target" ).submit(function( event ) {
            alert( "Handler for .submit() called." );
            event.preventDefault();
        });
}
</script>

But if I put the code below the form it usually works.

I want to put it in a .js file. But does not work in the head tag, only if I include after the form.

It is possible to make this code work in head tag?

4

3 回答 3

2

.load可能在触发事件之前未呈现表单。

检查窗口是什么,但你可能想写:

<script type="text/javascript">
    $(document).ready(function() {
        $( "#target" ).submit(function( event ) {
            alert( "Handler for .submit() called." );
            event.preventDefault();
        });
     });
</script>

检查此链接

如果您不使用该.ready方法,它将执行代码,搜索#target并找不到任何内容,因为渲染尚未传递您要定位的对象,因此无法找到它

于 2013-10-13T22:44:12.533 回答
2

你应该像这样初始化 jQuery:

$(document).ready(function() {
    $( "#target" ).submit(function( event ) {
        alert( "Handler for .submit() called." );
        event.preventDefault();
    });
});
于 2013-10-13T22:44:33.447 回答
0

尝试这个?

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {            
    $(document).on("submit", "#target", function(event) {
        alert("Handler for .submit() called.");
        event.preventDefault();
    });
});
</script>
于 2013-10-13T22:54:39.930 回答