2013-06-23 67 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>