var date;
document.getElementById("myButton1").onclick = function(){
date = document.getElementById("myText1").value;
}
console.log(date);
为什么这段代码不起作用?我是 js 新手,我无法在任何地方找到答案。
回答1
只需将 console.log(date)
放入函数中即可。像这样:
var date;
document.getElementById("myButton1").onclick = function(){
date = document.getElementById("myText1").value;
console.log(date)
}
回答2
如评论中所述,您的 console.log()
语句在 onclick
回调函数(设置 date
的 value)之前执行。 “回调”函数是稍后将在某个时间点(如果有的话)调用的函数,因此您的 JavaScript 代码不会逐行按顺序运行。
您的代码要求单击按钮以初始化 date
,因此在单击按钮之前,您不能期望 date
有一个 value,但您的 console.log()
会立即运行,之前date
得到一个 value。
这是你应该做的:
// Get your reference to the element(s) you know you'll need to
// work with just once and don't set your variable equal to a
// property value of the element - set it to the element itself.
// That way, if you ever decide you want a different property
// value, you already have the element reference and don't have
// to scan the document for the same element again.
const date = document.getElementById("myText1"); ;
// This line sets up an "event handling callback function" for
// the date element. The function's code will only run if/when the
// element gets its value changed and loses the focus. By setting up
// the event handler on the change event, you can be assured that
// the variable will always have the most up to date value
// Also, avoid event "propeties" like onclick
// as they are an older way to set up events and are not as robust
// as the modern standard way of using .addEventListener().
date.addEventListener("change", function(){
// The following line will only run if/when the button is clicked.
// If that happens before a date is specified in the myText1
// element, there won't be a value.
console.log(date.value);
});
<input type="date" id="myText1">