我试图找出为什么我的JavaScript和Jquery代码中的onclick函数无效。
我在JavaScript代码中引用我的“userInput”并将其存储在名为“userDate”的变量中。出于某种原因,用户输入不会被捕获/存储。
这是我的HTML:
<form role="form">
<p> Enter the date:
<input id="userInput" type="text" placeholder="yyyy-mm-dd" autofocus required></p>
<button id="convert" type="submit" class="btn btn-primary btn-lg" padding="center">
<span class="glyphicon glyphicon-euro"></span>
</button>
</form>
这是我的JS代码:
$(function () {
// cache the DOM element
var $currencies = $("#currencies");
var $userInput = $("#userInput");
// We are listening on the 'document',
// for a click on an element with an ID of #convert in the HTML
$("#convert").on("click", function() {
var userDate = $userInput;
// testing
console.log(userDate);
alert ("Handler for .click() is called.");
// AJAX call for GET request
$.ajax({
type: 'GET',
url: 'http://xxx.xx',
success: function(currencies) {
console.log("success func is called");
console.log(userDate);
$.each(currencies, function(i, currency){
$currencies.append("<div> EUR: " + currencies.rates["EUR"] + ", date: " + currencies.date + "</div>");
});
},
// error handling for my request
error: function() {
alert("error loading currencies");
}
});
});
});
答案 0 :(得分:3)
变化
var userDate = $userInput;
到
var userDate = $userInput.val();
$ userInput是对包含input元素的jquery对象的引用。使用.val()
返回该输入元素的文本值。