現在的問題是,你寫的代碼被執行的頁面加載時立即。
從你的代碼看起來,它看起來像你實際上希望窗體的按鈕來執行控制檯日誌。
我已經改變了你的代碼了一下,但在這裏,您會使用:
- 選擇表和輸入
- 聲明變量出範圍
- 綁定到表單提交事件
- 防止其實際提交
- 和記錄每您的例子安慰
下面
改變的代碼:
<script>
$(function() {
// Save a reference to the input
var input = $("input[name=first_name]"),
// Get the form itself
form = $("form[name=info]"),
// Storage for your first_name outside of the scope
first_name = false;
// Bind to the submit event on the form
form.bind('submit', function() {
// Set the first_name to the input's value
first_name = input.val();
// Log it out (per your example)
console.log(first_name);
// Return false to prevent the form from posting
return false;
});
});
</script>
<div id="content">
<form name="info">
First Name:
<input type="text" id="first_name" name="first_name">
<input type="submit" id="button">
</form>
</div>
我並不是說這是處理任何你正在試圖用表格做的最好的辦法,切實你不需要的按鈕的ID,並可能會想用選擇器的ID替換表單上的NAME。也建議使用ID選擇器來獲取輸入,因爲ID選擇器比選擇器快。 (感謝gnarf爲評論!)
的變量範圍也可能在你的例子有些奇怪,但上面的代碼應該是很好的學習:)
你肯定有您正在搜索的輸入什麼,根據你的代碼,您所呼叫負載的功能但輸入沒有指定的值。 – Nomad101
確保您已成功包含jQuery。 – Adil