2012-07-16 112 views
2

我在表單中爲我的網站創建了一個AJAX日誌;不過,我遇到了一些我認爲是jQuery中的bug。

代碼示例:

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Log In</title> 
    </head> 
    <body> 
     <div class="errors"></div> 
     <input type="username" placeholder="username"> 
     <input type="password" placeholder="password"> 
     <input type="submit" value="Log In"> 
    </body> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script> 
    <script> 
     $('input[type=submit]').click(function(){ 
      $(".errors").load(window.location.protocol + "//" + window.location.host + "?username=" + $("input[type=username]").val() + "&password=" + $("input[type=password]").val()); 
      return false; 
    }); 
    </script> 
</html> 

我知道一個事實,即它不是一個服務器端的問題。 $("input[type=username]").val()的返回值是undefined,而$("input[type=password]").val()的返回值是輸入的值。 謝謝大家! :)

+2

之前宣稱 「錯誤」,請確保您的測試用例是有效的第一。 [HTML Validator](http://validator.w3.org/)會告訴你你的錯誤。 – 2012-07-16 19:26:15

+0

人們認爲,從網上收穫插件使他們jQuery * ninjas * – Alexander 2012-07-16 19:48:31

回答

9

username不是有效的type屬性值。我猜你想要text,而這正是瀏覽器在遇到無法識別的類型時將默認使用的內容。因此,當您的代碼運行時,input實際上具有text類型,而不是username

有關有效type屬性值的完整列表,請參閱specification


附註 - 將您的jQuery版本升級到1.3.2或更高版本將解決此問題。我會盡快離開你目前使用的古代1.2.6!

查看working version (jQuery 1.7.2) here。如您在問題中所述,將包含的jQuery版本更改爲1.2.6,並記錄undefined

+0

是的,'username'應該用作'name'屬性的值。 – 2012-07-16 19:25:23

+0

好的,謝謝。 CSS支持用戶名類型。傻我。 – 2012-07-16 19:26:10

+0

@PatrickMurray - 查看我的更新。如果你更新jQuery到更新的版本,它會像你期望的那樣工作。儘管如此,我仍然強烈建議你不要使用'username'作爲'type'值。 – 2012-07-16 19:32:23