Javascript 为什么是';感情';显示为对象而不是我在文本字段中输入的内容?a
当我使用console.log(feelations)时,它会在 形式Javascript 为什么是';感情';显示为对象而不是我在文本字段中输入的内容?a,javascript,asynchronous,Javascript,Asynchronous,当我使用console.log(feelations)时,它会在 形式 但是,当我尝试向对象添加“感觉”并更新 我得到的ui是[object] 当你使用感觉的时候,价值观下降 在异步代码中,它工作得很好。这不是感情,不是价值=== .价值.价值 在这里输入Zipcode 你今天感觉怎么样? 生成 函数生成(e){ const zipcode=document.querySelector('#zip').value; const feelations=document.querySele
在这里输入Zipcode
你今天感觉怎么样?
生成
函数生成(e){
const zipcode=document.querySelector('#zip').value;
const feelations=document.querySelector(“#feelations”).value;
console.log(zipcode)
console.log(感觉)
getWeather(baseURL+zipcode+apiKey)
.then(功能(数据){
postData(数据)
})
.然后(更新)
}
/*函数获取Web API数据*/
const getWeather=async(url='')=>{
const response=等待获取(url);
试一试{
const weatherData=wait response.json();
weatherData['date']=新日期;
weatherData['Feelations']=Feelations;//除非使用feelations.value,否则它将显示为{}
控制台日志(天气数据);
返回天气数据;
}捕获(错误){
console.log('error',error);
}
}
感觉
不仅仅是任何随机对象,它是您的文本区域
元素。这种奇怪的行为是chrome和其他浏览器的一个坏特性;他们将ID为的DOM元素分配给以ID命名的全局变量,请阅读关于这个问题的更多信息:
由于您没有将features
从generate
传递到getWeather
,因此使用的features
是浏览器创建的全局变量,它是DOM元素,一个对象。换句话说,全局变量feelations
不是,因此使用它
要解决此问题,只需将features
作为参数从generate
传递到getWeather
,如下所示:
function generate (e) {
//...
getWeather(baseURL + zipcode + apiKey, feelings)
// ...
}
const getWeather = async (url, feelings) => {
// here the parameter 'feelings' is used rather than the global variable 'feelings'.
}
对不起,它只有在我使用…const feelations=document.querySelector(“#feelations”)时才起作用;然后进一步我使用feelations.values,但是当我仅仅使用const feelations=document.querySelector(“#feelations”).value时,它就不起作用了;然后再往下一点,我试着用“感觉”,它会返回[对象对象]哦,伙计,哈哈,谢谢!是的,这完全是一个愚蠢的错误。您是说document.getElementByID('feelations')>document.querySelector('#feelations')?谢谢again@ChrisCunningham否,
document.getElementByID('feelations')
与document.querySelector('#feelations')
相同。问题是浏览器已经创建了一个名为feelations
的变量,即domelement@StackSlave保持地方性更好,不必污染全球范围。此外,generate
可能被用作事件侦听器,因此缓存该值将无法正常工作expected@ChrisCunningham确切地你应该把它放在里面,像我给你展示的那样作为一个论点来传递哦,天哪,这真是太轻松了,所以你说的是感觉。价值最初甚至没有使用我声明的感觉,而是使用浏览器在全球范围内创建的感觉,这个名字恰好和我的声明同名,所以它对我隐瞒了它的起源@ChrisCunningham yesOops,我想我在这里发布了这样一条消息:在这种情况下,保持它的局部性的一点是每次生成火灾时都会得到元素。为什么要一次又一次地获取元素呢?
function generate (e) {
//...
getWeather(baseURL + zipcode + apiKey, feelings)
// ...
}
const getWeather = async (url, feelings) => {
// here the parameter 'feelings' is used rather than the global variable 'feelings'.
}