2013-06-23 68 views
0

我知道它是回来经常在很多帖子,但即使阅读几十个答案后一个问题,我仍然无法弄清楚什么是错在我的代码。防止默认事件 - jQuery的

关键是要防止默认提交,并在回答DIV检索响应数据。代码实际上做的是直接将我发送到geocoder.php页面。

非常感谢,

<script src="http://code.jquery.com/jquery-1.9.1.js"></script> 

<script> 
/* attach a submit handler to the form */ 
$("geostring").submit(function(event) { 

    /* stop form from submitting normally */ 
    event.preventDefault(); 

    /* get some values from elements on the page: */ 
    var $form = $(this), 
     term = $form.find('input[name="geo"]').val(), 
     url = $form.attr('action'); 

    /* Send the data using post */ 
    var posting = $.post(url, { s: term }); 

    /* Put the results in a div */ 
    posting.done(function(data) { 
    var content = $(data).find('#content'); 
    $("#answer").empty().append(content); 
    }); 
}); 
</script> 



<form action="http://winefy.alwaysdata.net/geocoder.php" method="POST" id="geostring"> 
<input type=text name="geo" placeholder="Address..." /> 
<input type="submit" value="Geocode" /> 
<div id="answer"></div> 
</form> 

回答

3

两件事情:

  1. 由于DCoder指出在下面的意见,你的选择缺少#。它应该是$("#geostring"),而不是$("geostring")

  2. 你尝试form元素存在之前附加的处理程序。所以$("#geostring")返回一个空的jQuery集合,并没有处理程序挂钩。

    只需将script标签form

    <form action="http://winefy.alwaysdata.net/geocoder.php" method="POST" id="geostring"> 
    <input type=text name="geo" placeholder="Address..." /> 
    <input type="submit" value="Geocode" /> 
    <div id="answer"></div> 
    </form> 
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
    
    <script> 
    /* attach a submit handler to the form */ 
    $("#geostring").submit(function(event) { 
    
        /* stop form from submitting normally */ 
        event.preventDefault(); 
    
        /* get some values from elements on the page: */ 
        var $form = $(this), 
         term = $form.find('input[name="geo"]').val(), 
         url = $form.attr('action'); 
    
        /* Send the data using post */ 
        var posting = $.post(url, { s: term }); 
    
        /* Put the results in a div */ 
        posting.done(function(data) { 
        var content = $(data).find('#content'); 
        $("#answer").empty().append(content); 
        }); 
    }); 
    </script> 
    

    更多:

    另外,如果你是不是在其中script标签去一些原因的控制,你可以使用jQuery的ready事件来延迟你的代码,直到DOM加载。

    $(function() { 
        // ...your code here... 
    }); 
    

    以上冗长:

    $(document).ready(function() { 
        // ...your code here... 
    }); 
    
+0

@Crowder Isin't只能通过加载所有的HTML元素之后执行的脚本浏览器? –

+0

@Vivek:不,脚本一遇到'script'标签就立即执行。 –

+0

非常感谢您的回答。我只是做了变化,但它不工作... 我用这个代码的自定义组件的一个Joomla视图,它改变什么? – justberare

1

您可以随时使用常用的方法:

<form onsubmit="return myFunc();"></form> 

<script type="text/javascript"> 
function myFunc(){ 
    // Your jQuery Code 
    return false; 
} 
</script>